Can I colour backgrounds of selected items in HTML select options with CSS only?

后端 未结 4 1997
慢半拍i
慢半拍i 2020-11-30 12:10

I\'ve searched around a lot and see people suggesting that:

::-moz-selection {background: red;}
::selection {background: red; }

..works for

相关标签:
4条回答
  • 2020-11-30 13:00

    ::selection doesn't apply to selected options; it applies to highlighted text. Either you're misinterpreting their suggestions, or what they said is flat-out wrong.

    According to this answer, you're supposed to be able to use option:checked for styling the selected items:

    #dropdowns option:checked {
        background: red;
    }
    

    But I haven't been able to get it to work for <select> or <select multiple> elements in this test fiddle.

    0 讨论(0)
  • 2020-11-30 13:06

    The right CSS Selector for you would be :checked

    ::selection is only for text that has been highlighted:

    • http://reference.sitepoint.com/css/pseudoelement-selection
    0 讨论(0)
  • 2020-11-30 13:07

    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%);
    }
    

    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%);
    }
    

    See the full demo here: http://codepen.io/marceltschopp/pen/PNyqKp

    0 讨论(0)
  • 2020-11-30 13:14

    I found this because I was having the same problem, I did find an odd solution that seems to work atleast with chrome and maybe others. The solution was to use an attribute selector. This seemed to work with chrome, I tested it in the js fiddle. A side note that the box did not immediately change color to background red but once I selected another option I could clearly see that it had indeed turned red. You can check it out in the jsfiddle listed above.

    http://jsfiddle.net/vzDvK/1/

    #dropdowns option[selected] {
        background: red;
    }
    
    0 讨论(0)
提交回复
热议问题