Quantico
Quantico

Reputation: 2446

setting the background color of a option under select

I found the following answer How to change select box option background color? but it did not work for me.

I have the following list in my html file

<select>
<option value="item 1" ></option>
<option value="item 2" ></option>
<option value="item 3"></option>
</select>

and the following css

select option[value="item 1"]{
    background: rgba(100,100,100,0.3);
}

but i am still getting an empty list with no background colors. What I am trying to get is some sort of a drop down with just colors and no text

something like this

enter image description here

thanks

Upvotes: 1

Views: 2230

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201588

You see an empty list because the option elements are empty. You cannot expect to be able to see the background of an empty area. But you can include e.g. a no-break space in the option element:

<option value="item 1" >&nbsp;</option>

You may still have problems with some browsers (styling of option elements has many oddities and browser differences, and the background and text color of the currently selected option tend to be fixed, by the browser, rather than CSS-settable).

A completely different approach is probably needed, though. While waiting for <input type=color> to be implemented during a decade or two, you need to set up color choices differently. There are many existing libraries that contain code for such things, but they tend to have accessility problems. Perhaps the simplest approach is to contructs simple use a table with radio buttons in one column, color samples and corresponding color names in another. Here, too, you would need to remember to set some content, like no-break space, into the element you use to present a color sample using a background color.

Upvotes: 0

davidkonrad
davidkonrad

Reputation: 85528

Go with nth-child() instead :

select option:nth-child(1) {
    background: rgba(100,100,100,0.3);
}

Then you are also not needed to change your CSS every time you change the values of the options.


Edit - I think you do

select option:nth-child(1) {
    background: red;
}
select option:nth-child(2) {
    background: yellow;
}
select option:nth-child(3) {
    background: green;
}
<select>
<option value="item 1">&nbsp;&nbsp;</option>
<option value="item 2">&nbsp;&nbsp;</option>
<option value="item 3">&nbsp;&nbsp;</option>
</select>

Upvotes: 2

Related Questions