Home >Web Front-end >CSS Tutorial >How to Create Multilevel Dropdown Menus in Bootstrap 4?

How to Create Multilevel Dropdown Menus in Bootstrap 4?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 03:36:13133browse

How to Create Multilevel Dropdown Menus in Bootstrap 4?

Multilevel Dropdown Menus in Bootstrap 4

Creating a multilevel dropdown in Bootstrap 4 is not as straightforward as with previous versions. To achieve it, you can use a combination of CSS and JavaScript. The following solution introduces the dropdown-submenu class for submenu items:

CSS:

.dropdown-submenu {
  position: relative;
}

.dropdown-submenu a::after {
  transform: rotate(-90deg);
  position: absolute;
  right: 6px;
  top: .8em;
}

.dropdown-submenu .dropdown-menu {
  top: 0;
  left: 100%;
  margin-left: .1rem;
  margin-right: .1rem;
}

JavaScript:

$('.dropdown-menu a.dropdown-toggle').on('click', function(e) {
  if (!$(this).next().hasClass('show')) {
    $(this).parents('.dropdown-menu').first().find('.show').removeClass('show');
  }
  var $subMenu = $(this).next('.dropdown-menu');
  $subMenu.toggleClass('show');

  $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {
    $('.dropdown-submenu .show').removeClass('show');
  });

  return false;
});

HTML:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse">

This solution allows for multi-level dropdown menus with a clean and responsive design. It works seamlessly with the default Bootstrap 4 styles and adds functionality for toggling the submenus.

The above is the detailed content of How to Create Multilevel Dropdown Menus in Bootstrap 4?. 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