Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 259
Web_Designer Avatar asked Dec 23 '11 18:12

Web_Designer


People also ask

What are the 3 types of selectors in CSS?

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)

What is difference between pseudo-class and pseudo element?

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.

When the pseudo-class selectors are applied to a link what states will the styles be applied to?

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 ...


1 Answers

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 */ 
like image 96
Emmett Avatar answered Nov 15 '22 16:11

Emmett