polydegmon polydegmon - 4 months ago 12
jQuery Question

How to set the color of a selected option in a select tag

I'm trying to set the color of the selected option in a select tag that has a size of 5 so it acts as a list box.

I can get it working when the select tag acts as a drop down but when I make it a list box the selected option is always grey when I unfocused it.

Here's a code example of what is happening. The first select tag is acting correctly, but as soon as I apply the size attribute, the color of the selected option will be grey.



select {
margin: 40px;
background: yellow;
color: #000;
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}
option:not(:checked) {
background-color: #FFF;
}

<select>
<option val="">Select Option</option>
<option val="1">Option 1</option>
<option val="2" selected>Option 2</option>
<option val="3">Option 3</option>
<option val="4">Option 4</option>
</select>
<br/>
<select size="5" multiselect>
<option val="">Select Option</option>
<option val="1">Option 1</option>
<option val="2" selected>Option 2</option>
<option val="3">Option 3</option>
<option val="4">Option 4</option>
</select>





After checking on JS Fiddle on different browsers, it appears to be a browser style that is getting set.

Below are images from Chrome, Firefox and Internet Explorer. Both chrome and firefox seem to set their own value, internet explorer will not though.

[![Chrome][1]][1]
[![FireFox][2]][2]
[![Internet Explorer][3]][3]

Answer

To do that, you have to set the background property of the option in CSS.

select,
select option:active,
select option:checked{
        margin:40px;
        background: yellow;
        color:#000;
        text-shadow:0 1px 0 rgba(0,0,0,0.4);
    }
    option:not(:checked) { 
        background-color: #FFF; 
    }
<select>
        <option val="">Select Option</option>
        <option val="1">Option 1</option>
        <option val="2" selected>Option 2</option>
        <option val="3">Option 3</option>
        <option val="4">Option 4</option>
    </select>
    <br/>
    <select size="5" multiselect>
        <option val="">Select Option</option>
        <option val="1">Option 1</option>
        <option val="2" selected>Option 2</option>
        <option val="3">Option 3</option>
        <option onfocus="this.style.background='red'" val="4">Option 4</option>
    </select>

Comments