Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

A Simple Guide to Bootstrap Dropdown: Customize and Implement

Bootstrap dropdowns are a crucial component in web design, providing a way to group related menu items, and making them easily accessible to users. They are toggleable, contextual overlays for displaying lists of links and more. They are made interactive with the included JavaScript Bootstrap dropdown plugin and are toggled by clicking, not by hovering, which is an intentional design decision.

This article aims to provide a comprehensive guide to understanding and using Bootstrap dropdowns. It will cover the basics of setting up the environment for using Bootstrap dropdowns, creating a basic dropdown, understanding the different options available for Bootstrap dropdowns, and more. The objective is to equip readers with the knowledge and skills to effectively implement and customize Bootstrap dropdowns in their web development projects. By the end of this article, readers should be able to create, customize, and manipulate Bootstrap dropdowns to suit their specific needs.

Getting Started

Before delving into the intricacies of customizing and implementing Bootstrap dropdowns, ensure you have your development environment set up. To do that, follow the following steps:

To integrate Bootstrap into your project, begin by including the Bootstrap CSS and JavaScript files. You can either download the files and host them locally or use a content delivery network (CDN). Here’s a basic example of including Bootstrap via CDN in the <head> section of your HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Include additional stylesheets or scripts if needed -->
    <title>Your Bootstrap Dropdown Project</title>
</head>
<body>
    <!-- Your content goes here -->
    <!-- Include Bootstrap JavaScript at the end of the body section -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Ensure that the Bootstrap version in the CDN links matches the version you want to use.

Before we proceed with the tutorial – If you use Bootstrap for your project, consider using Purecode Marketplace to access over 10000+ AI-generated ready-made templates and components to speed up your development process. Avoid the hassle with Purecode.

Do you want to skip ahead and learn via YouTube videos? Check out everything you need to know about how to create a dropdown using Bootstrap in this video tutorial:

Creating a Basic Dropdown

Now that we’ve set up our environment, let’s create a basic Bootstrap dropdown and explore the various components involved.

Code Example of a Basic Dropdown:

Let’s start with a simple example:

<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" id="basicDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Select an Option
    </button>
    <ul class="dropdown-menu" aria-labelledby="basicDropdown">
        <li><a class="dropdown-item" href="#">Option 1</a></li>
        <li><a class="dropdown-item" href="#">Option 2</a></li>
        <li><a class="dropdown-item" href="#">Option 3</a></li>
    </ul>
</div>

Explanation of Different Parts of the Dropdown Code:

  • <div class=”dropdown”>: This div serves as the container for the entire dropdown component. It groups the button and the dropdown menu.

  • <button class=”btn btn-primary dropdown-toggle” …>: Here, we have a button with the classes btn and btn-primary for styling, and dropdown-toggle to indicate that this button triggers a dropdown. The data-bs-toggle=”dropdown” attribute is crucial for enabling the dropdown functionality. The aria-haspopup and aria-expanded attributes assist in accessibility.

  • <ul class=”dropdown-menu” …>: This ul (unordered list) represents the dropdown menu. The dropdown-menu class styles the menu, and the aria-labelledby attribute associates it with the button using the button’s id.

  • <li><a class=”dropdown-item” href=”#”>Option 1</a></li>: Each list item (<li>) inside the dropdown menu represents an option. The dropdown-item class styles the individual items, and the anchor (<a>) tags provide the clickable area for each option.

Customizing the Dropdown Button and Menu:

Now, let’s explore how to customize the appearance of the dropdown button and menu:

Button Customization:

  • Change the button color by modifying the btn-primary class. Experiment with other Bootstrap button classes for different colors.

  • Adjust the text inside the button (Select an Option in the example) based on your specific use case.

// type button class btn
<button class="btn btn-danger dropdown-toggle" type="button" id="customButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Choose an Action
</button>

Menu Customization

  • Customize the styling of the dropdown menu using additional Bootstrap classes or your custom CSS.

  • Add icons or additional elements to each dropdown item.

<ul class="dropdown-menu" aria-labelledby="customButton">
    <li><a class="dropdown-item" href="#"><i class="bi bi-house-door"></i> Home</a></li>
    <li><a class="dropdown-item" href="#"><i class="bi bi-gear"></i> Settings</a></li>
    <li><a class="dropdown-item" href="#"><i class="bi bi-person"></i> Profile</a></li>
</ul>

By experimenting with these customization options, you can tailor the appearance of your Bootstrap dropdown to seamlessly integrate with your website’s design and enhance user interaction.

Bootstrap Dropdown Options

Bootstrap provides a range of options to customize the behavior and appearance of dropdowns. These include:

Alignment Options:

  • Control the alignment of the Bootstrap dropdown menu using classes like dropdown-menu-start and dropdown-menu-end.

  • Adjust the placement of the Bootstrap dropdown in relation to the button with classes like dropdown-menu-left and dropdown-menu-right.

Sizing Options:

  • Modify the size of the dropdown menu using classes like dropdown-menu-sm for small, dropdown-menu-lg for large, and dropdown-menu-xl for extra-large.

Disable Dropdown:

  • Prevent the Bootstrap dropdown from toggling by adding the disabled class to the button.

autoClose:

  • This option configures the auto close behavior of the dropdown. It can be set to true (the dropdown will be closed by clicking outside or inside the dropdown menu), false (the dropdown will be closed by clicking the toggle button and manually calling hide or toggle method), ‘inside’ (the dropdown will be closed (only) by clicking inside the dropdown menu), or ‘outside‘ (the dropdown will be closed (only) by clicking outside the dropdown menu).

boundary:

  • This option sets the overflow constraint boundary of the dropdown menu. By default, it’s clippingParents and can accept an HTMLElement reference (via JavaScript only).

display:

  • This option sets the display of the dropdown. By default, it uses Popper for dynamic positioning. You can disable this with static.

offset:

  • This option sets the offset of the dropdown relative to its target. You can pass a string in data attributes with comma-separated values like: data-bs-offset=”10,20″.

reference:

  • This option sets the reference element of the dropdown menu. It accepts the values of ‘toggle‘, ‘parent‘, an HTMLElement reference, or an object providing getBoundingClientRect.

Here’s an example of how to use some of these options:

<div class="dropdown">
 <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" data-bs-auto-close="outside" data-bs-boundary="viewport" data-bs-display="static" data-bs-offset="10,20" data-bs-reference="parent" aria-haspopup="true" aria-expanded="false">
  Dropdown Button
 </button>
 <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#">Option 1</a>
  <a class="dropdown-item" href="#">Option 2</a>
  <a class="dropdown-item" href="#">Option 3</a>
 </div>
</div>

Using the .active Class to Style Active Items:

The .active class is a powerful tool for visually indicating the active or selected item in the dropdown menu. Apply this class to the desired <li> element to highlight the active option.

<ul class="dropdown-menu" aria-labelledby="activeItemDropdown">
    <li><a class="dropdown-item" href="#">Option 1</a></li>
    <li><a class="dropdown-item active" href="#">Option 2 (Active)</a></li>
    <li><a class="dropdown-item" href="#">Option 3</a></li>
</ul>

By including the .active class, you can provide users with a clear visual cue, enhancing the overall usability of your dropdown menus.

Using the aria-current Attribute:

To ensure accessibility and convey the active state to assistive technologies, use the aria-current attribute. This attribute indicates the current item within a set of related elements. Apply it to the active item in your dropdown menu.

<ul class="dropdown-menu" aria-labelledby="ariaCurrentDropdown">
    <li><a class="dropdown-item" href="#" aria-current="page">Option 1</a></li>
    <li><a class="dropdown-item" href="#">Option 2</a></li>
    <li><a class="dropdown-item" href="#">Option 3</a></li>
</ul>

By including the aria-current=”page” attribute on the active item, you contribute to a more inclusive user experience for individuals relying on assistive technologies.

Understanding and utilizing these dropdown options provides you with the flexibility to tailor your Bootstrap dropdowns to meet specific design and user interaction requirements.

Dropdown Menu Items

The versatility of Bootstrap dropdowns extends beyond mere links and buttons. In this section, we’ll explore how to create non-interactive dropdown items, add text utilities, and employ custom CSS to elevate the visual appeal of your dropdown menus.

How to Add Headers to Label Sections of Actions:

Not all items in a dropdown need to be interactive. Bootstrap provides the .dropdown-item-text class for creating non-interactive, text-based items. This is particularly useful for displaying headers or descriptive text within your dropdown menu.

<ul class="dropdown-menu" aria-labelledby="nonInteractiveDropdown">
    <li><span class="dropdown-item-text">Section Header</span></li>
    <li><a class="dropdown-item" href="#">Option 1</a></li>
    <li><a class="dropdown-item" href="#">Option 2</a></li>
</ul>

The .dropdown-item-text class ensures that the item appears as plain text without the interactive styling associated with regular dropdown items.

How to Place Any Freeform Text within a Dropdown Menu:

For scenarios where freeform text is needed within the dropdown, include a <p> or <span> element with the .dropdown-item-text class.

<ul class="dropdown-menu" aria-labelledby="freeformTextDropdown">
    <li><p class="dropdown-item-text">Additional Information:</p></li>
    <li><span class="dropdown-item-text">Lorem ipsum dolor sit amet.</span></li>
</ul>

By using the .dropdown-item-text class, you can seamlessly integrate non-interactive text into your dropdown menu.

How to Add Dividers to Separate Different Sections:

To visually separate different sections within your dropdown menu, employ the .dropdown-divider class. This adds a horizontal line between items.

<ul class="dropdown-menu" aria-labelledby="dividerDropdown">
    <li><a class="dropdown-item" href="#">Option 1</a></li>
    <li><a class="dropdown-item" href="#">Option 2</a></li>
    <li role="separator" class="dropdown-divider"></li>
    <li><a class="dropdown-item" href="#">Option 3</a></li>
    <li><a class="dropdown-item" href="#">Option 4</a></li>
</ul>

This simple yet effective technique enhances the visual organization of your dropdown content.

How to Align the Dropdown Menu:

Bootstrap provides classes for adjusting the alignment of your dropdown menu relative to the button. The classes dropdown-menu-start and dropdown-menu-end can be utilized to align the dropdown to the start or end of the button, respectively.

<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" id="alignedDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Actions
    </button>
    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="alignedDropdown">
        <li><a class="dropdown-item" href="#">Option 1</a></li>
        <li><a class="dropdown-item" href="#">Option 2</a></li>
    </ul>
</div>

By using these alignment classes, you have precise control over the positioning of your dropdown menu.

Styling Further with Custom CSS or Text Utilities:

For additional customization, you can leverage custom CSS or Bootstrap’s text utilities to style your dropdown items. Text utilities, such as .text-muted for muted text, can be applied directly to the <a> or <span> elements within the dropdown menu.

<ul class="dropdown-menu" aria-labelledby="customStylingDropdown">
    <li><a class="dropdown-item text-muted" href="#">Subdued Option</a></li>
    <li><a class="dropdown-item text-danger" href="#">Critical Option</a></li>
    <li><a class="dropdown-item text-success" href="#">Success Option</a></li>
</ul>

Custom CSS can also be employed for more intricate styling:

<style>
    .custom-dropdown-item {
        color: #3498db; /* Set your desired color */
        font-weight: bold;
        /* Add more custom styles as needed */
    }
</style>

<ul class="dropdown-menu" aria-labelledby="customCssDropdown">
    <li><a class="dropdown-item custom-dropdown-item" href="#">Styled Option</a></li>
    <li><a class="dropdown-item custom-dropdown-item" href="#">Another Styled Option</a></li>
</ul>

If you don’t want to use the Bootstrap classes, you can also style your dropdown menu using CSS. From the code above:

  • The <style> tag is used to include CSS rules within the HTML document. In this case, it defines a new CSS class called custom-dropdown-item which was assigned to each <li>. This class sets the text color of the dropdown items to a shade of blue (#3498db) and makes the text bold. You can add more custom styles as needed.

Code Example of a Dropdown with Different Types of Menu Items:

Let’s combine these concepts into a comprehensive example:

<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" id="mixedItemsDropdown" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Explore Options
    </button>
    <ul class="dropdown-menu" aria-labelledby="mixedItemsDropdown">
        <li><span class="dropdown-item-text">Categories</span></li>
        <li><a class="dropdown-item" href="#">Electronics</a></li>
        <li><a class="dropdown-item" href="#">Clothing</a></li>
        <li><a class="dropdown-item" href="#">Books</a></li>
        <li role="separator" class="dropdown-divider"></li>
        <li><span class="dropdown-item-text">Promotions</span></li>
        <li><a class="dropdown-item text-success" href="#">Discounts</a></li>
        <li><a class="dropdown-item text-danger" href="#">Clearance</a></li>
    </ul>
</div>

In this example:

  • We use .dropdown-item-text to create non-interactive headers.

  • Text utilities like .text-success and .text-danger add color to specific items.

  • A dropdown-divider creates a visual separator between categories.

Advanced Customization

When it comes to mastering Bootstrap dropdowns, advanced customization goes beyond basic styling. In this section, we’ll explore advanced techniques for triggering dropdowns and handling JavaScript events, providing you with the tools to create highly interactive and dynamic user interfaces.

Triggering Dropdowns:

Dropdowns can be triggered in various ways, and understanding the available options is crucial for tailoring the user experience to your specific needs.

  1. Hover vs. Click:

    • Hover Trigger: By default, Bootstrap dropdowns are triggered on click. However, you can enable hover-triggered dropdowns by adding the hover class to the dropdown container. This is particularly useful for quick previews or navigation menus.

      <div class="dropdown hover">
          <!-- Dropdown content goes here -->
      </div>
    • Click Trigger: The standard click-triggered dropdown is the default behavior. Users click the button to reveal the dropdown menu.

      <div class="dropdown">
          <!-- Dropdown content goes here -->
      </div>
  2. Choosing the Right Trigger:

    • Hover: Ideal for providing quick previews or additional information without the need for a click. Useful for desktop interfaces.

    • Click: Suitable for most scenarios, especially when a deliberate action is required. Works well on both desktop and mobile devices.

JavaScript Events:

Harnessing JavaScript events allows you to create dynamic and responsive interactions within your dropdowns. Bootstrap provides a range of events to handle various actions.

  1. Handling Opening and Closing:

    • The show.bs.dropdown and hide.bs.dropdown events are triggered when a dropdown is about to be shown or hidden, respectively.

      <script>
          const myDropdown = new bootstrap.Dropdown(document.getElementById('myDropdown'));
          
          myDropdown._element.addEventListener('show.bs.dropdown', function () {
              // Custom logic when the dropdown is about to be shown
          });
          
          myDropdown._element.addEventListener('hide.bs.dropdown', function () {
              // Custom logic when the dropdown is about to be hidden dropdowns toggle contextual overlays, default dropdown clickable
          });
      </script>
  2. Handling Item Selection:

    • The click.bs.dropdown event is triggered when a dropdown item is clicked.

      <script>
          const myDropdown = new bootstrap.Dropdown(document.getElementById('myDropdown'));
          
          myDropdown._element.addEventListener('click.bs.dropdown', function (event) {
              const selectedItem = event.target; // Access the clicked item
              // Custom logic for handling item selection
          });
      </script>

These examples showcase the basic structure of event handling with Bootstrap dropdowns. Customizing the event handling allows you to implement features like dynamic content loading, animations, or data manipulation based on user interactions.

By incorporating advanced customization techniques, you can create Bootstrap dropdowns that not only enhance user engagement but also provide a seamless and interactive experience. In the next sections, we’ll delve into best practices for responsive design, performance optimization, and accessibility considerations to further elevate your mastery of Bootstrap dropdowns.

Best Practices of using Bootstrap dropdown

Here’s a table of best practices for using Bootstrap dropdowns:

Best PracticeDescription
Use Popper.jsDropdowns in Bootstrap are built on a third-party library, Popper.js, which provides dynamic positioning and viewport detection. Be sure to include popper.min.js before Bootstrap’s JavaScript or use bootstrap.bundle.min.js / bootstrap.bundle.js which contains Popper.js.
Click to ToggleDropdowns are made interactive with the included Bootstrap dropdown JavaScript plugin. They’re toggled by clicking, not by hovering; this is an intentional design decision.
Use Dropdown ClassesUse the “dropdown” class to create the dropdown container, “dropdown-toggle” class to create the dropdown button, and “dropdown-menu” class to create the dropdown menu.
Use Dropdown-Item ClassUse the “dropdown-item” class for individual items in the dropdown menu.
Responsive DesignEnsure that your dropdown menus are responsive and work well on different devices and screen sizes.
AccessibilityMake sure your dropdown menus are accessible to keyboard users.
Offline AvailabilityConsider making your dropdown menus available offline if your website or application needs to be accessible without an internet connection.

You can get access to advanced Dropdown components that follow best practices from PureCode, PureCode provides customizable components such as Dropdowns to help you build interactive and responsive web pages faster. This reduces the time to build repetitive templates and lets you focus on defining the logic for your web application. Start here.

What You Have Learned

In this comprehensive guide, we’ve covered everything from the basics of Bootstrap dropdowns to advanced customization options. We’ve explored how to set up the environment for using Bootstrap dropdowns, create a basic dropdown, understand different options available for Bootstrap dropdowns, style the dropdown button and menu, and even go beyond the standard options with advanced customization methods.

Bootstrap dropdowns are a powerful tool in web design, providing a way to group related menu items together, making them easily accessible to users. By understanding how to use and customize them, you can greatly enhance the user experience of your web applications. In the end, the key to mastering Bootstrap dropdowns is practice. So, don’t hesitate to experiment with different options and customizations to see what works best for your specific needs. Happy coding!

For further learning, here are some video resources that provide a comprehensive guide to creating and customizing Navbars in Bootstrap:

Victor Yakubu

Victor Yakubu