Nav Links and Hover

You have a nav bar with nav links, like this:

Screenshot 1An example navbar

And when you hover over one of the links, you want a change to happen. What you want is the background color to fill the height of your nav container, like this:

Screenshot 2Navbar on hover - with top and bottom padding

But right now, when you hover over one of your nav links, the background color only covers the size of the text, like this:

Screenshot 3Navbar on hover - no top and bottom padding

What’s going on?

First let’s take a look at the nav bar HTML, where your anchor elements (your links) are nested inside <li> elements.

HTML

<nav>
  <ul>
    <li><a href="#">CASA</a></li>
    <li><a href="#">ABOUT</a></li>
    <li><a href="#">SIGN-IN</a></li>
  </ul>
</nav>

CSS

nav ul {
  list-style-type: none;
  margin: 0px;
}

nav ul li {
  display: inline;
}

Remember that to use the :hover CSS pseudo-class, in this case, you apply :hover to your anchor (<a>) elements. For example:

nav a:link {
  color: white;
}

nav a:hover {
  color: #5C8033;
  background-color: white;
}

The background-color rule will do its job and change the color of the content area of your anchor element, which is the size of the text’s line-height. And which is what you see in Screenshot 3 above.

Your goal is Screenshot 2, however, where the background-color is nice and meaty and fills the size of the nav container’s height.

So how do you fix this unfortunate state of affairs?

You do so by making your <a> elements warm and cozy with padding values. Of course, your specific values will depend on the height of your nav container.

nav a:link {
  color: white;
  padding: 14px 7px;
}

nav a:hover {
  color: #5C8033;
  background-color: white;
}

Now, if you hover over your anchor elements, you’ll see a Screenshot 2-type result. Party.

And last thing, when you’re dealing with anchor pseudo-classes, remember the correct ordering in your CSS!

a:link
a:visited
a:hover
a:focus
a:active

Twitter share ⤴