HTML <optgroup> Tag
HTML <optgroup> tag groups elements in а drop-down list <select>, defined by the <option> tag. See examples.
HTML <optgroup> tag groups <option> tags together. The required <label> attribute defines the group heading, which appears in bold, while the options inside are automatically indented. (The <option> tag defines items in a drop-down list created by the <select> tag.)
The <optgroup> tag is considered to be a form element.
Syntax
The <optgroup> tag comes in pairs. The content is written between the opening (<optgroup>) and closing (</optgroup>) tags.
Example of the HTML <optgroup> tag:
Example of a drop-down list
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<select>
<optgroup label="Books">
<option value="html">HTML</option>
<option value="css">CSS</option>
</optgroup>
<optgroup label="Snippets">
<option value="java">Java</option>
<option value="linux">Linux</option>
<option value="git">Git</option>
</optgroup>
</select>
</body>
</html>Result
The browser will render a drop-down list with two groups:
- Books: HTML, CSS
- Snippets: Java, Linux, Git
Example of the HTML <optgroup> tag with the disabled attribute:
Example of the HTML <optgroup> Tag
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<select>
<optgroup disabled="disabled" label="Quizzes">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JavaScript</option>
<option value="php">PHP</option>
</optgroup>
<optgroup label="Snippets">
<option value="git">Git</option>
<option value="angularjs">AngularJS</option>
</optgroup>
</select>
</body>
</html>Result
The browser will render a drop-down list with two groups:
- Quizzes (disabled): HTML, CSS, JavaScript, PHP
- Snippets: Git, AngularJS
Attributes
| Attribute | Value | Description |
|---|---|---|
| disabled | disabled | Indicates that the selection of the group elements is disabled. |
| label | text | Defines a label for the group, which will be displayed as a heading in the drop-down list. Required attribute. |
The <optgroup> tag supports the Global attributes and the Event Attributes.
How to style an HTML <optgroup> Tag
You can use CSS to change the appearance of the group heading and its options:
optgroup {
font-weight: bold;
color: #333;
}
optgroup option {
font-weight: normal;
padding-left: 15px;
}Practice
What is the function of the HTML 'optgroup' tag?