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
CSS :selected pseudo class similar to :checked, but for <select> elements
提问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
:checked
pseudo-class initially applies to such elements that have the HTML4selected
andchecked
attributes
的
:checked
伪类最初适用于具有这样的HTML4元素selected
和checked
属性
Source: w3.org
资料来源:w3.org
So, this CSS works, although styling the color
is 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.
color
does not work, background-color
either, 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;
}