polydegmon
polydegmon

Reputation: 605

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.

enter image description hereenter image description hereenter image description here

Upvotes: 1

Views: 2776

Answers (2)

Hector Barbossa
Hector Barbossa

Reputation: 5528

You can try adding a background gradient in case of multi select like below. You need to add properties to make this work in cross browser though.

select[multiselect] option:checked {
    background: -moz-linear-gradient(left, yellow 0%, yellow 100%);
 }

Upvotes: 0

EddNewGate
EddNewGate

Reputation: 537

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>

Upvotes: 2

Related Questions