Html CSS :selected 伪类类似于 :checked,但用于 <select> 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8619406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:08:30  来源:igfitidea点击:

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

htmlcsscss-selectorspseudo-class

提问by Web_Designer

Is there a way to style the currently selected <option>element in a <select>element?

有没有办法在<option>元素中设置当前选定元素的样式<select>

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.

然后我可以为当前选择的选项元素提供背景颜色吗?这样我就可以设置当前在关闭的下拉列表中可见的选项的样式。

回答by Emmett

the :checkedpseudo-class initially applies to such elements that have the HTML4 selectedand checkedattributes

:checked伪类最初适用于具有这样的HTML4元素selectedchecked属性

Source: w3.org

资料来源:w3.org



So, this CSS works, although styling the coloris not possible in every browser:

所以,这个 CSS 是有效的,虽然color在每个浏览器中都不可能设置样式:

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 closeddropdown as well, you could try reversing the logic:

要在关闭的下拉列表中设置当前选定选项的样式,您可以尝试反转逻辑:

select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */

回答by Antwan

Actually you can only style few CSS properties on :modifiedoption elements. colordoes not work, background-coloreither, but you can set a background-image.

实际上,您只能在:modified选项元素上设置几个 CSS 属性的样式。 color也不起作用,background-color但您可以设置一个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.

适用于壁虎/webkit。

回答by Neoweiter

This worked for me :

这对我有用:

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