Previous Section  < Day Day Up >  Next Section

Recipe 5.3 Setting Styles for Select and Option Elements

Problem

You want to alter the look of list menus in a form by changing the color and font, as in Figure 5-5.

Figure 5-5. The select and option elements with styles applied
figs/csscb_0505.gif


Solution

Use a type selector to associate styles with select elements:

select { 

 color: white; 

 background-color: blue;

 font-size: 0.9em;

}

option {

 padding: 4px;

}

Discussion

Unlike input form elements, there is only one type of select element, so associating styles to that element is straightforward and can be done through a type selector. Styling the option element is just as easy.

To stylize alternating options in a select list, first include the class attribute in the option element:

<select name="Topping_ID" size="6" multiple>

 <option value="1">Pepperoni</option>

 <option value="2" class="even">Sausage</option>

 <option value="3">Green Peppers</option>

 <option value="4" class="even">Pineapple</option>

 <option value="5">Chicken</option>

 <option value="6" class="even">Ham</option>

 <option value="7">Olives</option>

 <option value="8" class="even">Onions</option>

 <option value="9">Red Peppers</option>

</select>

Then set up the CSS rules for the two sets of option elements, making sure that the option elements with an even value (as noted by the class selector even) look different from the others. For example, option elements with an even selector have a background color of red, while the "regular" option elements have a background color of blue (see Figure 5-6):

select { 

 font-size: 0.9em;

}

option {

 color: white; 

 background-color: blue;

}

option.even {

color: blue;

 background-color: red;

}

Figure 5-6. Alternating styles applied to select and option elements
figs/csscb_0506.gif


See Also

Recipe 5.1 for information on how to change the color and size of input element text.

    Previous Section  < Day Day Up >  Next Section