Use the optgroup element to group select options

Sometimes it is useful to group the options of an HTML select element. Many developers use extra option elements and non-breaking spaces to create the visual appearance of hierarchical options, but there is another way: the often forgotten optgroup element.

To create a group of options, wrap them in an optgroup element. To give the group a label, use the label attribute. Here is a simple example:

<label for="cars">Choose a car brand:</label>
<select name="cars" id="cars">
	<option value="none" selected>None</option>
	<optgroup label="Swedish">
		<option value="saab">Saab</option>
		<option value="volvo">Volvo</option>
	</optgroup>
	<optgroup label="French">
		<option value="citroen">Citroën</option>
		<option value="peugeot">Peugeot</option>
		<option value="renault">Renault</option>
	</optgroup>
</select>

And here is how the browser you are currently using will render the above example:

One caveat is that assistive technology support for the optgroup element and the label attribute is inconsistent, as noted in Creating Accessible Forms at WebAIM and the WCAG 2 technique H85: Using OPTGROUP to group OPTION elements inside a SELECT.

This post is a Quick Tip. Background info is available in Quick Tips for web developers and web designers.

Posted on October 5, 2009 in Quick Tips, Accessibility, (X)HTML