Is it possible to style a select
element based on what option
is selected with CSS only? I am aware of existing JavaScript solutions.
I tried to style the option element itself, but this will give style only to the option element in the list of options, not to the selected element.
select[name="qa_contact"] option[value="3"] {
background: orange;
}
http://jsfiddle.net/Aprillion/xSbhQ/
If not possible with CSS 3, will CSS 4 subject selector help in the future - or will this stay a forbidden fruit to CSS?
Update 2022: using :has
pseudo-class can help to style the select itself (in browsers that support both the :has
pseudo-class and styling of <select>
), but it only works for HTML attributes, so only if the select has the option explicitly selected initially. It will not work dynamically without JS - after the user changes selection, that will only change DOM properties, but not the HTML attributes on which CSS attribute selectors depend:
select:has(option[selected][value="3"]) {
background: orange;
}
Yes, in 2023 this is now possible using both :has
and :checked
. The accepted and top-voted answers are out-of-date.
select:has(> option[value="3"]:checked) {
background: orange;
}
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>