Bootstrap ยท Chapter 20 of 43

Bootstrap Dropdowns

Dropdowns show a list of links or actions when a user clicks a toggle button. They require Bootstrap's JavaScript (and Popper.js, included in the bundle) to handle showing, hiding and positioning the menu.

A dropdown consists of a toggle button with data-bs-toggle="dropdown" and a sibling .dropdown-menu containing .dropdown-item links.

Syntax
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown">Menu</button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Item</a></li>
  </ul>
</div>

Building a dropdown

Wrap a button and a menu in a .dropdown div. The button needs data-bs-toggle="dropdown", and the menu is a <ul class="dropdown-menu"> with <li><a class="dropdown-item">.

Dropdown extras

Add .dropdown-divider for a horizontal line between groups of items, and .dropdown-header for a small non-clickable section label inside the menu.

Example 1 (html)
<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
    Options
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Edit</a></li>
    <li><a class="dropdown-item" href="#">Duplicate</a></li>
    <li><hr class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">Delete</a></li>
  </ul>
</div>
Output
A button labeled Options that reveals a menu with Edit, Duplicate, a divider, and Delete

Clicking the toggle button shows the dropdown-menu, and dropdown-divider groups related items visually.

Example 2 (html)
<div class="dropdown">
  <a class="btn btn-outline-dark dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">Account</a>
  <ul class="dropdown-menu">
    <li><h6 class="dropdown-header">Signed in as Amy</h6></li>
    <li><a class="dropdown-item" href="#">Profile</a></li>
    <li><a class="dropdown-item" href="#">Logout</a></li>
  </ul>
</div>
Output
An Account link that opens a menu with a non-clickable header and two clickable items

dropdown-header displays a label like 'Signed in as Amy' without acting as a clickable link.

Key points

  • Dropdowns need Bootstrap's JavaScript bundle to function.
  • The toggle element needs data-bs-toggle="dropdown".
  • .dropdown-menu holds .dropdown-item links.
  • .dropdown-divider and .dropdown-header help organize menu content.
๐Ÿ’ก Note: Dropdown menus automatically reposition themselves near screen edges thanks to Popper.js.

๐Ÿ“ Quick Quiz

1. What attribute triggers a dropdown to open?

2. Which class wraps the list of dropdown links?

3. Which library helps position the dropdown menu correctly?