How can I scroll part of a Bootstrap 4 dropdown menu?

ghz 8months ago ⋅ 173 views

I want add more options in my second and third dropdown menu at desktop mode, but the list is too long. How can I set y-scroll?

demo

I try to add max-height to the dropdown, but problem is that now sub menu are not shown.they are hidden.

@media (min-width: 1024px) {
    nav.navbar.bootsnav ul.nav .dropdown-menu .dropdown-menu{
        margin-top: -2px;
        max-height:300px;
        overflow-y:auto
    }
   }

Answers

To enable vertical scrolling in your dropdown menu while ensuring that the submenus are still visible, you can set a maximum height for the dropdown menu and enable overflow-y to allow scrolling. However, to ensure that the submenus are not hidden, you also need to adjust the positioning of the submenus. Here's how you can modify your CSS:

@media (min-width: 1024px) {
    nav.navbar.bootsnav ul.nav .dropdown-menu {
        max-height: 300px; /* Set maximum height for the dropdown menu */
        overflow-y: auto; /* Enable vertical scrolling */
    }
    
    /* Adjust the position of submenus to ensure they are visible */
    nav.navbar.bootsnav ul.nav .dropdown-menu .dropdown-menu {
        top: 0; /* Ensure submenu starts from the top of the dropdown menu */
        left: 100%; /* Position the submenu to the right of the dropdown menu */
        margin-top: 0; /* Reset margin-top */
    }
}

In this CSS code:

  • We set a maximum height for the dropdown menu and enable vertical scrolling using max-height and overflow-y properties.
  • We adjust the position of the submenu to ensure it starts from the top of the dropdown menu and is positioned to the right of the dropdown menu using top and left properties.
  • We reset the margin-top property to ensure proper alignment of the submenu.

By adjusting the positioning of the submenus, you can ensure that they are not hidden when the dropdown menu is scrolled vertically. Adjust the max-height value as needed to fit your design requirements.