One
<option>
elements are often inserted as dividers, or worse, convoluted JavaScript solutions that emulates this behavior with generic markup and complicated CSS.
The simple, perfectly valid and accessible solution is to use the <optgroup>
element. It’s used for grouping <option>
elements in a <select>
list into sections. It’s perfectly safe to use since it’s supported across all browsers.
Here’s an example of how to create a sectioned select list with pets.
<label for="pets">Pets</label> <select> <optgroup label="Dogs"> <option>Golden Retriever</option> <option>Doberman</option> </optgroup> <optgroup label="Cats"> <option>Burma</option> <option>Siamese</option> </optgroup> </select>
This code will result in this select list:
Example
There’s one big additional benefit and that is that the labels in the list are not clickable and can therefor not be selected by mistake.
So the next time you want to create a select list with sections, look for <optgroup>
first.
Leave a Reply