Selectable <optgroup> in HTML <select> tag

Solution 1:

I don't think you can but you can easily reproduce the visual style with css and thus only have options in your select, so everything is selectable.

.optionGroup {
    font-weight: bold;
    font-style: italic;
}
    
.optionChild {
    padding-left: 15px;
}
<select multiple="multiple">
    <option value="0" class="optionGroup">Parent Tag</option>
    <option value="1" class="optionChild">Child Tag</option>
    <option value="2" class="optionChild">Child Tag</option>
</select>

The multiple attribute allow you to select more than one row (with ctrl click). You can remove it if it is not what you want. It was to show you that everything became selectable and that is looking the same as with optiongroup element.

Solution 2:

This is not possible with plain html. A few browsers (mozilla) would allow you to achieve something similar using css, but at the time of this writing the majority of browsers (webkit, et.al) do not support styling of html select elements.

However there are a number of javascript libraries designed to enhance html-select widgets and provide missing features such as the one you've requested. To name a few:

  • Select2
  • Chosen
  • jQuery UI SelectMenu

Solution 3:

Until this is supported in an html standard, any and all answers given have been problematic, including:

  1. Class attributes are allowed on the children of a select, but if/how the style is applied to the element varies enormously between browsers and browser versions.
  2. Prefixing with &nbsp; will have the consequence that if the select element is narrower than the selected option, the visual effect will not be pleasing, with readable text hidden off to the right (see example below).
  3. Any style you apply will not necessarily fit with the styling the user of the browser has become accustomed to. bold and italic is Firefox, but not necessarily every browser. Many browsers apply a style including gray color in order to help indicate the optgroup is NOT selectable
  4. The concept of a select optgroup label will not necessarily be expected by the user.

This has lead me to conclude the best way to work around the problem is either to use a library like UI-Selectable for all selects throughout your site (for consistency), OR use the first option in the optgroup to represent selecting all the children, with a clear description (such as 'ALL Swedish cars'):

<select multiple="multiple">
   <optgroup label="Parent">
      <option value="0" class="optionChild">ALL Children</option>
      <option value="1" class="optionChild">Child Tag 1</option>
      <option value="2" class="optionChild">Child Tag 2</option>
   </optgroup>
</select>

.my-select {
  width: 60px;
}
<select class="my-select">
  <option>Parent</option>
  <option selected="selected">&nbsp;&nbsp;&nbsp;Child</option>
</select>