Tuesday, July 19, 2011

Styling optgroups

An earlier post noted that I had managed to go a long time without learning about the optgroup feature that allows items in a drop down list to be grouped under sub-headings. Yesterday, I wanted to change the default look, so I did a quick google search to see if anyone had any nice styling examples that I could adapt - this is my normal design policy as I am a poor original designer.

Basically, there were none (this makes me feel better - apparently I am not the only web developer who has overlooked this feature). So I set out to develop my own. My first style rule was a simple selector on optgroup:

optgroup {
    background-color: #023373;
    color: #ffffff;
}

I was hoping just the group title would be in dark blue with white text, but instead the entire group was—which meant that then entire list was so colored. So I added a second rule:
optgroup option {
    background-color: white;
    color: black;
}
This got it. Now my headers were blue bars with white text, but the rest of the list was back to normal. All that remained was to give the group titles a bit better look: I wanted them centered with a little spacing. My final rules:

optgroup {
    background-color: #023373;
    color: #ffffff;
    font-weight: bold;
    font-style: normal;
    padding: 3px 0 0 0;
    text-align: center;
}
        
optgroup option {
    background-color: #ffffff;
    color: #000000;
    padding: 0 0 0 1em;
    text-align: left;
}

Note that I had to reset the styling for the option. I initially had left off the padding rule for the option elements, and the actual list items were flush left.

Here's an example of the final look:



No comments: