1

Having this HTML

<select>
  <option style="color:green">green</option>
  <option style="color:red">red</option>
</select>

I'd like to make the selectbox inherit its color from selected option. Alas

select { color: inherit; }

doesn't do the trick. Is there any pure CSS solution?

Edit: I know there is simple javascript solution. I don't want to make fancy select box, just inherit the color from the selected option.

Jan Turoň
  • 29,041
  • 21
  • 114
  • 159
  • 1
    This might be beyond the capabilities of CSS (affecting a parent by a child's state)... are you okay with a JavaScript solution? – scunliffe Oct 19 '15 at 12:57
  • 1
    You will need to use javascript – FBHY Oct 19 '15 at 12:58
  • 1
    Possible duplicate of [How to style a – dippas Oct 19 '15 at 13:04

3 Answers3

3

This is rather rough, but would work (requires JavaScript)

<select onchange="this.style.color = this.options[this.selectedIndex].style.color;">
  <option style="color:green">green</option>
  <option style="color:red">red</option>
</select>

Demo: http://jsfiddle.net/pbjvqhbc/

scunliffe
  • 60,441
  • 24
  • 124
  • 159
  • Thanks for tip, but I know this simple solution, I just wonder if there is any CSS way, that's why I tagged it CSS, not javascript. – Jan Turoň Oct 19 '15 at 13:27
  • Sorry @JanTuroň it can't be done in pure CSS. CSS can only modify an element's style based on it's own attributes, class, ID, etc. and the parent hierarchy it is contained within. – scunliffe Oct 19 '15 at 14:49
1

Editing a parent element based on the state of it's children can't be done in pure CSS yet. You'll have to use JavaScript to pull this off.

As mentioned in the comments, this answer is based on using jQuery rather than vanilla JS

$(document).ready(function() {
    $('select').on('change', function() {
        $(this).css('color', $(this).find(':selected').css('color'));
    });
});
Lynch
  • 870
  • 4
  • 11
  • 1
    You should point out that the solution you provided is jQuery and not vanilla Javascript. =) – Marco Hengstenberg Oct 19 '15 at 13:28
  • 1
    Forgot for a moment I wasn't browsing the jQuery tags! Edited my answer though, thanks for mentioning it – Lynch Oct 19 '15 at 13:34
  • And I answered your question, by saying it cannot be done in pure CSS. I, like another answerer, gave you an option that would work purely as a courtesy. We could have answered no and left you to it, instead we tried to help you as best we could, while **still** answering your explicit question – Lynch Oct 19 '15 at 15:13
0

Unfortunately the answer to your question is: no.

There is no way you would be able to style the select itself related to the choice of the user with CSS alone.

There are interesting selectors like :checked or :target but none will help you styling the parent element.