How to Make the Bootstrap 4 Navbar Dropdown Work on Hover Instead of Click

If you have ever created your own Bootstrap Navbar with a dropdown menu, the first thing you may notice is that you have to click the parent link to reveal the sub-menu. This is an intentional design decision according to Mark Otto:

“The purpose of a hover state is to indicate something is clickable (underlined text) or to provide some quick information (full URL in a tooltip). The purpose of a click is to actually do something, to take explicit action.” – Mark Otto

It’s a valid point but there are always situations where people prefer the hover method. To be honest, not a lot of menus even feature the down chevron, so the hover element makes it clearer that there are sub-menu items to be clicked.

In this tutorial, we are going to be using Bootstrap 4 with the Jumbotron template as an example to show you how simple it is to achieve.

Prefer to dive straight into the CodePen, then click here.

Let’s Begin

Okay, let’s say we have the following HTML markup:


   <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarsExampleDefault">
    <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">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
        <div class="dropdown-menu" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

<main role="main">

  <!-- Main jumbotron for a primary marketing message or call to action -->
  <div class="jumbotron">
    <div class="container">
      <h1 class="display-3">Menu Dropdown on Hover</h1>
      <p>Hey ho, so let's make your dropdown menu work on hover instead of click.</p>
      <p><a href="https://silvawebdesigns.com/" target="_blank" class="btn btn-primary btn-lg" role="button" rel="noopener noreferrer">Learn more &raquo;</a></p>
    </div>
  </div>

  <div class="container">
    <!-- Example row of columns -->
    <div class="row">
      <div class="col-md-4">
        <h2>Learn</h2>
        <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
      </div>
      <div class="col-md-4">
        <h2>Code</h2>
        <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
      </div>
      <div class="col-md-4">
        <h2>Repeat</h2>
        <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p>
        <p><a class="btn btn-secondary" href="#" role="button">View details &raquo;</a></p>
      </div>
    </div>

    <hr>

  </div> <!-- /container -->

</main>

<footer class="container">
  <p>&copy; Silva Web Designs 2020</p>
</footer>

Now, the important part, to get the CSS to work on hover instead of click, we will be adding the following CSS:


body {
    padding-top: 60px;
    padding-bottom: 40px;
}

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
}

.dropdown:hover .dropdown-menu {
    display: block;
}

.nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu {
    margin-top: 0;
}

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
}
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;
}

The key feature of the CSS is simply adding display: block; to the following class element; .dropdown:hover .dropdown-menu

And it’s really as simple as that.

We will need to include the Bootstrap Assets which as of the time of writing, the latest are:

With the CSS code, simply add the stylesheet <link> into your <head> before all other stylesheets to load your CSS.


<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

The with the JS, they require jQuery, and their own JavaScript plugins. Place the following scripts near the end of your pages, right before the closing tag, to enable them. jQuery must come first, then the Bootstrap JavaScript plugins.

Bootstrap uses the jQuery’s slim build, but the full version is also supported:


<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

And there we have it, it’s as simple as that really! Some common problems can be due to the order/positioning of the CSS/JS files, but other than that, it’s a simple feature to implement. You can also make it a bit fancier as well and add some animations into the mix to make the dropdown menu slide down/up. If you would like any help with this, don’t hesitate to get back to us in the comments and we’ll show you how it’s done.

We hope you’ve enjoyed this article and happy coding devs!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How To Create a 3D Flip Box using CSS

How you ever wanted to create a 3D Flip Box? Well, you are in the right place. This is basically a div which flips when you hover over a certain element and can be achieved using CSS alone. You can use JavaScript and jQuery, but if you can use just CSS alone, it’s always better right? We’re not a ‘huge’ fan of the effect in 2020 but I guess it’s always down to personal preference really. I guess it’s good if you want to compress the amount of information you have on the page as you can add whatever content you want on the front and back of these flip elements. So let’s get started…

How To Create a Flip Box

You can view this effect on CodePen by clicking here.

So firstly, add your HTML markup:


<div class="flip-box">
  <div class="flip-box-inner">
    <div class="flip-box-front">
      <h2>Front Side</h2>
    </div>
    <div class="flip-box-back">
      <h2>Back Side</h2>
    </div>
  </div>
</div>

Now, we just need to add the following CSS:


* {
  font-family: 'Arial', sans-serif;
}

/* The Container for Flip Box - Set the width and height to whatever you want. */
.flip-box {
  background-color: transparent;
  width: 300px;
  height: 200px;
  perspective: 1000px; /* Remove this if you don't want the 3D effect */
}

/* This container is needed to position the front and back side */
.flip-box-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  transition: transform 0.8s;
  transform-style: preserve-3d;
}

/* Do an horizontal flip when you move the mouse over the flip box container */
.flip-box:hover .flip-box-inner {
  transform: rotateY(180deg);
}

/* Position the front and back side */
.flip-box-front,
.flip-box-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Style the front side */
.flip-box-front {
  background-color: #e1e1e1;
  color: #000;
}

/* Style the back side */
.flip-box-back {
  background-color: #20232c;
  color: #FFF;
  transform: rotateY(180deg);
}

Note: We added flex positioning to these elements; .flip-box-front, .flip-box-back to center the content within the box. Remove the following attributes if you want the content to be displayed from the top; display: flex;, align-items: center; and justify-content: center;

Now, let’s take this one step further, fancy doing a vertical flip instead? Then check the below.

How To Create a Vertical Flip Box

To do a vertical flip instead of a horizontal, all we need to do is use rotateX method instead of rotateY as follows:


.flip-box:hover .flip-box-inner {
  transform: rotateX(180deg);
}

.flip-box-back {
  transform: rotateX(180deg);
}

Again, you can check out the CodePen example by clicking here.

And that’s it, flippin’ simple right?

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

CSS: Avoid image hover first time blinking / flicker

If you’ve ever used image replacement on hover for your background images then you will have noticed this annoying ‘blinking/flicker’ the first time you hover over the element. That’s because we are not pre-loading the image and so I would recommend loading the image on load to avoid this.

Here is a simple and effective CSS image preloading technique I have used several times. You can load several images by placing content: url() url() url()… etc.


body:after {
    display: none;
    content: url(path/to/image-hovered.jpg) url(path/to/another-image-hovered.jpg);
}

This can be done in various other ways but the CSS method is my preferred method.

If you want to go ahead and use a JavaScript method you can use the code below:-


function preloader() {
	if (document.images) {
		var img1 = new Image();
		var img2 = new Image();
		var img3 = new Image();

		img1.src = "http://domain.com/path/to/image-001.gif";
		img2.src = "http://domain.com/path/to/image-002.gif";
		img3.src = "http://domain.com/path/to/image-003.gif";
	}
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
addLoadEvent(preloader);

I hope this helps!

If you want to see this in action, have a look at this CodePen we created here.

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

How to make Bootstrap menu dropdown on hover rather than click

To get the menu to automatically drop on hover then this can achieved using basic CSS. You need to work out the selector to the hidden menu option and then set it to display as block when the appropriate li tag is hovered over. Taking the example from the twitter bootstrap page, the selector would be as follows:


ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;    
}

However, if you are using Bootstrap’s responsive features, you will not want this functionality on a collapsed navbar (on smaller screens). To avoid this, wrap the code above in a media query:


@media (min-width: 992px) {
  ul.nav li.dropdown:hover > ul.dropdown-menu {
    display: block;
  }
}

Then to make the dropdown’s appear more smoothly, we can apply a fade in effect as follows:-


.dropdown .dropdown-menu{
    display: block; 
    opacity:0;
    -webkit-transition: all 200ms ease-in;
    -moz-transition: all 200ms ease-in;
    -ms-transition: all 200ms ease-in;
    -o-transition: all 200ms ease-in;
    transition: all 200ms ease-in;
}
.dropdown:hover .dropdown-menu {
    display: block;
    opacity: 1;
}

Hope this helps 🙂

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share