Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Cheers :/

Setup: Using Chrome for Mac

like image 524
Mere Development Avatar asked Feb 16 '12 10:02

Mere Development


People also ask

How do I change the background color of a selection in HTML?

To change the selected option background-color CSS style, we can set the style attribute of the select and option elements. to set the whole select element to background color 009966 and color FFF . Then we override the the styles in the option elements with style="background: white; color: black;" .

How do you style the option of an HTML select element?

You can use inline styles to add custome styling to <option> tags. For eg : <option style="font-weight:bold;color:#09C;">Option 1</option> This will apply the styles to this particular <option> element only. You can also use <option value="" disabled> <br> </option> to add a line-break between the options.


2 Answers

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

like image 136
Marcel Tschopp Avatar answered Oct 11 '22 10:10

Marcel Tschopp


::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.

like image 25
BoltClock Avatar answered Oct 11 '22 10:10

BoltClock