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

眉间皱痕 提交于 2019-11-26 03:22:43

问题


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.


回答1:


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 */



回答2:


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.




回答3:


This worked for me :

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


来源:https://stackoverflow.com/questions/8619406/css-selected-pseudo-class-similar-to-checked-but-for-select-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!