Is there a way to style the currently selected <option>
element in a <select>
element?
I could then give a background color to the currently selected option element? That way I can style the option that's currently viewable in the closed dropdown.
Simple selectors (select elements based on name, id, class) Combinator selectors (select elements based on a specific relationship between them) Pseudo-class selectors (select elements based on a certain state)
Pseudo-classes enable you to target an element when it's in a particular state, as if you had added a class for that state to the DOM. Pseudo-elements act as if you had added a whole new element to the DOM, and enable you to style that.
Pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator ( :visited , for example), the status of its content (like :checked on certain form elements), or the position of the mouse (like :hover ...
the
:checked
pseudo-class initially applies to such elements that have the HTML4selected
andchecked
attributes
Source: w3.org
So, this CSS works, although styling the color
is not possible in every browser:
option:checked { color: red; }
An example of this in action, hiding the currently selected item from the drop down list.
option:checked { display:none; }
<select> <option>A</option> <option>B</option> <option>C</option> </select>
To style the currently selected option in the closed dropdown as well, you could try reversing the logic:
select { color: red; } option:not(:checked) { color: black; } /* or whatever your default style is */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With