Search code examples
htmlcssflexboxnav

Hover underlining only text within a flexbox


I'm trying to get an underline to work on hover on a vertical nav made with flexbox. On a horizontal nav without flexbox the hover underline works fine, but as soon as flexbox is added the underline spans the entire box rather than just under the text.

See how in the first snippet below it works as intended but as soon as I make main_nav vertical with flexbox in the second snippet the underline breaks.

How can I fix this so it underlines correctly while keeping the nav vertical?

#wrapper {
  width: 100%;
  height: 300px;
  background-color: black;
}


#wrapper #main_nav {
  //display: flex;
  //flex-direction: column;
}

.nav_item {
  text-decoration: none;
  color: white;
  display: inline-block
}

.nav_item:after {
  display: block;
  content: '';
  width: 0;
  height: 2px;
  background-color: white;
}

.nav_item:hover:after {
  width: 100%;
  transition: width 150ms ease-in;
}
<div id="wrapper">
    <nav id="main_nav">
      <a href="#" class="nav_item">Item1</a>
      <a href="#" class="nav_item">Item2</a>
      <a href="#" class="nav_item">Item3</a>
      <a href="#" class="nav_item">Item4</a>
    </nav>
</div>

#wrapper {
  width: 100%;
  height: 300px;
  background-color: black;
}


#wrapper #main_nav {
  display: flex;
  flex-direction: column;
}

.nav_item {
  text-decoration: none;
  color: white;
  display: inline-block
}

.nav_item:after {
  display: block;
  content: '';
  width: 0;
  height: 2px;
  background-color: white;
}

.nav_item:hover:after {
  width: 100%;
  transition: width 150ms ease-in;
}
<div id="wrapper">
    <nav id="main_nav">
      <a href="#" class="nav_item">Item1</a>
      <a href="#" class="nav_item">Item2</a>
      <a href="#" class="nav_item">Item3</a>
      <a href="#" class="nav_item">Item4</a>
    </nav>
</div>


Solution

  • Use display: inline-flex; instead of display:flex;, which is block-level.