css - Style <select> element based on selected <option> -


is possible style select element based on option selected css only? aware of existing javascript solutions.

i tried style option element itself, give style option element in list of options, not selected element.

select[name="qa_contact"] option[value="3"] {     background: orange; } 

http://jsfiddle.net/aprillion/xsbhq/

if not possible css 3, css 4 subject selector in future - or stay forbidden fruit css?

unfortunately, yes - not possible css. mentioned in answers , comments this question, there no way make parent element receive styling based on children.

in order you're wanting, have detect of children (<option>) selected, , style parent accordingly.

you could, however, accomplish simple jquery call, follows:

html

<select>   <option value="foo">foo!</option>   <option value="bar">bar!</option> </select> 

jquery

var $select = $('select'); $select.each(function() {     $(this).addclass($(this).children(':selected').val()); }).on('change', function(ev) {     $(this).attr('class', '').addclass($(this).children(':selected').val()); }); 

css

select, option { background: #fff; } select.foo, option[value="foo"] { background: red; } select.bar, option[value="bar"] { background: green; } 

here working jsfiddle.

back question future of selectors. yes - "subject" selectors intended mention. if/when ever go live in modern browsers, adapt above code to:

select { background: #fff; } !select > option[value="foo"]:checked { background: red; } !select > option[value="bar"]:checked { background: green; } 

as side-note, there still debate whether ! should go before or after subject. based on programming standard of !something meaning "not something". result, subject-based css might wind looking instead:

select { background: #fff; } select! > option[value="foo"]:checked { background: red; } select! > option[value="bar"]:checked { background: green; } 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -