Can I have the background color of selected elements in HTML selections only using CSS?

I searched a lot and saw people say that:

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

.. works to color the background of the currently selected items into an item with multiple selection items. (Note: I mean the selected elements, not the elements with focus).

I can't get this to work. Am I doing it wrong?

 #dropdowns select::selection { background: red; } 

Greetings: /

Setup: Use Chrome for Mac

+6
source share
4 answers

Instead of setting a background color, you can also set a linear gradient as the background:

 option:checked { background: red linear-gradient(0deg, red 0%, red 100%); } 

This works in IE11 and the latest Chrome and Firefox. Safari just ignores it. Not tested 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

+23
source

::selection does not apply to the selected parameters; it applies to the selected text. Either you misinterpret your proposals, or what they said is wrong.

According to this answer, you should use option:checked to style the selected elements:

 #dropdowns option:checked { background: red; } 

But I could not get it to work for <select> or <select multiple> elements in this test script .

+2
source

The correct CSS selector for you would be :checked

:: selection is for selected text only:

0
source

I found this because I had the same problem, I found a weird solution that seems to work with at least chrome and possibly others. The solution was to use an attribute selector. It seemed to work with chrome, I tested it in a js script. The party notes that the box did not immediately change color to red, but as soon as I chose another option, I could clearly see that it really turned red. You can check this in the jsfiddle above.

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

 #dropdowns option[selected] { background: red; } 
0
source

Source: https://habr.com/ru/post/908605/


All Articles