Home >Web Front-end >CSS Tutorial >How to Make Bootstrap Dropdowns Activate on Hover?

How to Make Bootstrap Dropdowns Activate on Hover?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 20:19:14849browse

How to Make Bootstrap Dropdowns Activate on Hover?

Bootstrap Dropdown Activation on Hover

In your Bootstrap navbar with dropdown menus, you seek to activate the dropdowns on hover instead of the default onClick behavior.

Solution Using CSS:

The simplest solution to achieve this is through CSS. Add the following snippet to your CSS file:

.dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0; /* Remove the gap for seamless display */
}

This CSS rule sets the dropdown menu to be displayed as a block element when its parent dropdown is hovered over. Additionally, it cancels out the initial margin-top to ensure the menu appears seamlessly below the dropdown button.

Example Implementation:

<!-- Dropdown with onClick behavior -->
<ul class="navbar-nav">
  <li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" data-toggle="dropdown">
      Dropdown
    </a>
    <div class="dropdown-menu">
      <a class="dropdown-item" href="#">Action</a>
    </div>
  </li>
</ul>

<!-- Dropdown with onHover behavior using CSS -->
<ul class="navbar-nav">
  <li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" data-toggle="dropdown">
      Dropdown
    </a>
    <div class="dropdown-menu">
      <a class="dropdown-item" href="#">Action</a>
    </div>
  </li>
</ul>

By applying the CSS rule to the latter dropdown, it will activate on hover, while the first dropdown retains its onClick behavior.

Note that this CSS solution requires your dropdown menus to be consistently nested within the dropdown parent element.

The above is the detailed content of How to Make Bootstrap Dropdowns Activate on Hover?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn