CSS :selected pseudo class similar to :checked, but for <option> elements

HtmlCssCss SelectorsPseudo Class

Html Problem Overview


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.

Html Solutions


Solution 1 - Html

> the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked 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 */

Solution 2 - Html

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

option:hover,
option:focus,
option:active,
option:checked {
  background: linear-gradient(#5A2569, #5A2569);
}

<select>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Works on gecko/webkit.

Solution 3 - Html

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

Solution 4 - Html

The css from the accepted answer also doesn't work for me. But this inline style works. Tested on Firefox 86 and Chrome 88.

<select>
    <option value="1" style="display:none;" selected>One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWeb_DesignerView Question on Stackoverflow
Solution 1 - HtmlEmmettView Answer on Stackoverflow
Solution 2 - HtmlAntwanView Answer on Stackoverflow
Solution 3 - HtmlNeoweiterView Answer on Stackoverflow
Solution 4 - Htmluser2366975View Answer on Stackoverflow