Can I colour backgrounds of selected items in HTML select options with CSS only?(我可以仅使用 CSS 为 HTML 选择选项中选定项目的背景着色吗?)
问题描述
我搜索了很多,看到有人建议:
I've searched around a lot and see people suggesting that:
::-moz-selection {background: red;}
::selection {background: red; }
..用于为多选表单项中当前选定项的背景着色.(注意:我指的是选中的项目,而不是有焦点的项目).
..works for colouring the background of the currently selected items in a multiple select form item. (Note: I mean the selected items, not the items with focus).
我无法让它工作.我做错了吗?
I can't get this to work. Am I doing it wrong?
#dropdowns select::selection {
background: red;
}
干杯:/
设置:使用 Mac 版 Chrome
Setup: Using Chrome for Mac
推荐答案
除了设置背景色,还可以设置线性渐变作为背景:
Instead of only setting a background-color you can also set a linear-gradient as background:
option:checked {
background: red linear-gradient(0deg, red 0%, red 100%);
}
这适用于 IE11 和最新的 Chrome 和 Firefox.Safari 只是忽略它.没有测试 IE/Edge.
This works in IE11 and latest Chrome and Firefox. Safari just ignores it. Did not test IE/Edge.
如果您只想为重点多选设置背景颜色,您可以使用以下代码段:
If you want to set the background color only for focused multi-selects you can use this snippet:
select[multiple]:focus option:checked {
background: red linear-gradient(0deg, red 0%, red 100%);
}
在此处查看完整演示:http://codepen.io/marceltschopp/pen/PNyqKp
这篇关于我可以仅使用 CSS 为 HTML 选择选项中选定项目的背景着色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!