Bootstrap 3 Dropdowns
Add dropdown menus without writing any JavaScript.
Bootstrap includes a component for adding dropdown menus. The JavaScript is included with the default Bootstrap JS file and you can use it simply by adding the CSS classes — no further JavaScript required.
Example
Here's an example of a Bootstrap dropdown:
Explanation of Code
Creating the Dropdown
As you can see from the above example, creating a dropdown is easy with Bootstrap. It is done purely with HTML markup. Bootstrap handles the JavaScript behind the scenes.
Here are the key steps for creating a Bootstrap dropdown:
- Wrap the dropdown trigger element within an element with Bootstrap's
.dropdownclass, or another element that usesposition: relative; - Add Bootstrap's
.dropdown-toggleclass and adddata-toggle="dropdown"to the trigger element (i.e. the element that users click on to expand the dropdown). In the above example, the trigger is a<button>element. - Use the
<ul>element with a class of.dropdown-menuto build the actual dropdown menu.
The Caret
In the above example we also add a small down triangle (caret) to indicate that it is a dropdown. We add this by using Bootstrap's .caret class applied to a <span> element.
About the ARIA Attributes
You might also notice that the above example has some ARIA attributes. These have been added for accessibility purposes. Here's an explanation of the ARIA attributes used with the above dropdown.
aria-haspopup- Indicates that the element has a popup context menu or sub-level menu. Its value can be either
true(the element has a popup) orfalse(the element does not have a popup). aria-expanded- Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. Possible values are
true,false, and undefined (default). aria-labelledby- Identifies the element (or elements) that labels the current element. It provides the user with a recognizable name of the object.
Dropup Menu
You can reverse the dropdown so that it becomes a "dropup" menu:
You might have noticed that Bootstrap automatically reverses the caret when using a dropup, indicating to the user that the list will appear above the button.
Align Right
You can add Bootstrap's .dropdown-menu-right class to the .dropdown-menu class to align the menu to the right of its parent.
Headers
Add a header to your dropdown menu by adding a applying Bootstrap's .dropdown-header class to a <li> element.
Dividers
Add dividers to your dropdown menu by adding a applying Bootstrap's .divider class to a <li> element, and also adding role="separator".
Disabled Menu Items
Disable a menu item by applying Bootstrap's .disabled class to its <li> tag.
Split Dropdowns
You can also create split dropdown menus with button groups.