views:

685

answers:

2

With CSS I can set font and background colours for the individual options of a dropdown "select" list; however, these colours only show up in the actual dropdown. The colours shown in the box on the page when the list is not open are still the defaults.

Currently I have a list with many dropdown boxes having a few options, and it would be useful to be able to colour each option so that the selection is immediately obvious. Converting to radio buttons or other input is not really feasible. (My clients are rather picky. :-p)

+2  A: 

IE gets it right if that's any consolation ;)

You'll need some JavaScript for it to work in other browsers:

<select onchange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
    <option style="background-color:yellow">Item 1</option>
    <option style="background-color:lightyellow">Item 2</option>
</select>

Even nicer with css class names:

<select
    onchange="this.className=this.options[this.selectedIndex].className"
    class="important">
    <option class="important" selected="selected">Item 1</option>
    <option class="sorta-important">Item 2</option>
</select>

And your css:

.important { background-color:yellow; }
.sorta-important { background-color:lightyellow; }

That way you keep your presentation details separate and your class names meaningful.

Crescent Fresh
Thanks, that works great.
+1  A: 

I did it in jQuery:

<select id="ddlColors" style="background-color: White;">
    <option style="background-color: Aqua;">1</option>
    <option style="background-color: Blue;">2</option>
    <option style="background-color: Fuchsia;">3</option>
    <option style="background-color: Gray;">4</option>
</select>
<script>
    $("select").change(function() {
        $("select").css("background-color", $("select option:selected").css("background-color"));
    })
    .change();
</script>
JMP