dans.blog


The miscellaneous ramblings and thoughts of Dan G. Switzer, II

Stupid HTML Tricks: Add a non-selectable option to a select element

Occasionally I've run into a situation where I've wanted to add some whitespace between two options in a <select /> element. The most common solution I've seen people use is to include an empty <option></option> tag pair. While this works, it adds a blank entry that the user can actually select—which means you have to add some code to handle the selection of what is designed to just be used for whitespace.

A better solution is to use an empty <optgroup /> that is disabled:

<select>
  <option>Value 1</option>
  <!---// add a non-selectable space between options, the margin-top is for FF spacing //--->
  <optgroup disabled="disabled" style="margin-top: 1em;"></optgroup>
  <option>Value 2</option>
</select>

This will add a non-selectable blank line between "Value 1" and "Value 2". Here's an example:

I use this technique often before normal <optgroup /> tags as it helps make the menu look a little cleaner by adding some separation between the options and works with all modern browsers. Best of all, you don't have to worry about handling those empty <option /> tags!