Lesson 24 +10 XP

Dropdowns

A dropdown menu shows a list of links when a button is clicked. Bootstrap dropdowns are built with a few classes and data attributes.

Basic dropdown

Code

html
<div class="dropdown">
  <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">

### Dropdown button
  </button>
  <ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">Link 1</a></li>
    <li><a class="dropdown-item" href="#">Link 2</a></li>
    <li><a class="dropdown-item" href="#">Link 3</a></li>
  </ul>
</div>

The key parts

  • .dropdown wraps everything.
  • .dropdown-toggle adds the caret arrow on the button.
  • data-bs-toggle=&quot;dropdown&quot; enables the toggle behavior.
  • .dropdown-menu is the menu container.
  • .dropdown-item styles each menu link.

Dropdown dividers

Use &lt;hr class=&quot;dropdown-divider&quot;&gt; to separate groups of items:

Code

html
<ul class="dropdown-menu">
  <li><a class="dropdown-item" href="#">Item 1</a></li>
  <li><a class="dropdown-item" href="#">Item 2</a></li>
  <li><hr class="dropdown-divider"></li>
  <li><a class="dropdown-item" href="#">Separated item</a></li>
</ul>

Dropdown header

Use .dropdown-header for a small heading inside the menu:

Code

html
<div class="dropdown-header">Dropdown header</div>

Dropdown positions

  • .dropup opens the menu upward.
  • .dropend opens to the right.
  • .dropstart opens to the left.
Code

html
<div class="dropup">
  ...
</div>

TL;DR

  • Use .dropdown with .dropdown-toggle and data-bs-toggle=&quot;dropdown&quot;.
  • Menu items use .dropdown-menu and .dropdown-item.
  • .dropdown-divider separates items.
  • .dropup, .dropend, .dropstart change the direction.