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
Release: 2024-12-20 03:36:13
Original
104 people have browsed it

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;
}
Copy after login

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;
});
Copy after login

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">
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template