How to Create Optgroup in HTML: Syntax and Examples
Use the
<optgroup> tag inside a <select> element to group related <option> elements. The label attribute on <optgroup> defines the group name shown in the dropdown.Syntax
The <optgroup> tag groups related options inside a <select> dropdown. Use the label attribute to name the group. Inside <optgroup>, place multiple <option> tags.
<select>: The dropdown list container.<optgroup label="Group Name">: Defines a group with a visible label.<option>: Individual selectable items inside the group.
html
<select> <optgroup label="Group 1"> <option value="1">Option 1</option> <option value="2">Option 2</option> </optgroup> <optgroup label="Group 2"> <option value="3">Option 3</option> <option value="4">Option 4</option> </optgroup> </select>
Output
A dropdown with two groups labeled 'Group 1' and 'Group 2', each containing two options.
Example
This example shows a dropdown menu with fruit and vegetable groups. Each group has its own label and options inside.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Optgroup Example</title> </head> <body> <label for="food">Choose a food:</label> <select id="food" name="food"> <optgroup label="Fruits"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </optgroup> <optgroup label="Vegetables"> <option value="carrot">Carrot</option> <option value="broccoli">Broccoli</option> <option value="spinach">Spinach</option> </optgroup> </select> </body> </html>
Output
A dropdown labeled 'Choose a food:' with two groups: 'Fruits' containing Apple, Banana, Orange; and 'Vegetables' containing Carrot, Broccoli, Spinach.
Common Pitfalls
Common mistakes when using <optgroup> include:
- Forgetting the
labelattribute, which makes the group name invisible. - Placing
<optgroup>outside of a<select>element, which is invalid. - Using
<option>tags directly inside<select>without grouping when groups are needed for clarity.
html
<!-- Wrong: Missing label attribute -->
<select>
<optgroup>
<option value="1">Option 1</option>
</optgroup>
</select>
<!-- Right: Label attribute added -->
<select>
<optgroup label="Group 1">
<option value="1">Option 1</option>
</optgroup>
</select>Output
The first dropdown shows options without a group label; the second shows the group label 'Group 1' above the option.
Quick Reference
Tips for using <optgroup>:
- Always include the
labelattribute to name the group. - Use
<optgroup>only inside<select>. - Group related options to improve user experience.
- Do not nest
<optgroup>inside another<optgroup>.
Key Takeaways
Use
Always provide the label attribute on
Do not place
Grouping options improves dropdown clarity and user experience.
Each