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!
Comments
I agree about breaking semantics. Not a big fan of it either. I wish all browsers were created equal--it would prevent lots of hacks.
As for your question about CSS, no you can not. The only browser that allows you to add margin or padding to an option tag is Firefox--which is what the margin-top hack is for.
Support for CSS with the option tag is very limited in most browsers. This is a little dated, but still pretty accurate as to what's supported:
http://www.456bereastreet.com/lab/styling-form-con...
