Benjamin Benjamin - 3 months ago 279
CSS Question

Keep background color for option when changing focus

In this example : https://jsfiddle.net/pfc1qauz/10/ when I select 2 and changing focus to C (anything on the right part), the background color of 2 has become grey. How to keep it red when it is not focus ?

HTML:

<select class="multiselect-left" size=4>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class="multiselect-right" size=4>
<option>A</option>
<option>B</option>
<option>C</option>
</select>


CSS:

option{
background: #F00;
}


Thanks,

Answer Source

This is likely the result of a browser-specific style. As you can see if you use the Developer Tools (F12) within Google Chrome :

select:-internal-list-box option:checked {
    background-color: -internal-inactive-list-box-selection;
    color: -internal-inactive-list-box-selection-text;
}

Even if you were to add this same style using your own values, it still would not override it properly :

select:-internal-list-box option:checked {
    background-color: red!important;
    color: #FFF!important;
}

This is applying the style that you are seeing to the checked options within any <select> elements and it cannot really be directly overridden.

<select> elements are notoriously difficult to style in any kind of cross-browser sense. If it's something that you really need to handle, you would likely need to use a Javascript-based solution like select that would override the default <select> as a facade that uses <div> or other elements for styling purposes.