I have a bootstrap 4 navbar menu:
<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="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
So normally, dropdown menu opens on click. It's okay for mobile devices but I want it open on hover for big screens. So when navbar menu is collapsed it should open on click but if it's not it should open on hover. How can I achieve that?
Use a @media query for the breakpoint of the navbar-expand-lg:
@media (min-width: 992px) {
.dropdown:hover .dropdown-menu {
display: block;
}
}
https://www.codeply.com/go/uFPbKuv8GO
The fundamental part of the answers given here is:
@media (min-width: 992px) {
.dropdown:hover .dropdown-menu {
display: block;
}
}
This works, but has a defect. Say you hover the mouse over .dropdown. The .dropdown-menu appears. When you lower the mouse into .dropdown-menu, it will close if you don't move the mouse fast enough, as the "hover" condition is lost at the border between .dropdown and .dropdown-menu.
This can be fixed by nudging the position of .dropdown-menu upwards, so there is no border where the "hover" condition is lost.
The default bootstrap position of .dropdown-menu is top: 100%. Override that as follows:
@media (min-width: 992px) {
.dropdown:hover .dropdown-menu {
display: block;
top: 95%;
}
}
This way the dropdown stays open even if the user moves the mouse into it slowly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With