Search code examples
csshoververtical-alignmentline-breaks

Vertically aligned fixed-height multi-line list item with hover behavior for entire item (not just text)


I have a menu and need the following behavior:

When hovering over a list item (not just the text), the background should change color and the text turn white. (works only on single-line). Sitewide, all spans have the color set and I cannot change (included at top of css) so I need to overwrite it for just this menu.

I have found similar questions but haven't found anything that covers this specifically.

HTML

<ul id="navbar">
  <li><a href="#">Line 1</a></li>
  <li><a href="#"><span>Line 2 <br>Line 2 - 2nd Row</span></a></li>
  <li><a href="#"><span>Line 3<br>Line 2 - 2nd Row</span></a></li>
  <li><a href="#">Line 4</a></li>
</ul>

CSS

span {
  color: #feb800;
}

#navbar {
  height: 105px;
  line-height: 105px;
  vertical-align: middle;
}

ul#navbar {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  text-align: center;
  width: 100%;
  white-space: nowrap;
  padding-left: 0;
  font-size: 0; // remove whitespace to prevent extra space before list item
}

#navbar li {
  float: none;
  display: inline-block;
  width: 25%;
  text-transform: uppercase;
  vertical-align: middle;
}

#navbar li {
  border-right: 2px solid #feb800;
}

#navbar li:last-child {
  border-right: none;
}

#navbar a {
  display: block;
  color: #feb800;
  font-weight: bold;
  font-size: 16px;
  text-decoration: none;
}

#navbar a {
  height: 105px;
}

#navbar a:hover {
  background-color: #feb800;
  color: #ffffff;
}

#navbar a span {
  line-height: normal;
  vertical-align: middle;
  display: inline-block;
}

#navbar a span:hover {
  color: #ffffff;
}

Solution

  • Move :hover to li element. In the case above instead of whole #navbar a:hover selector put:

    #navbar li:hover {
      background-color: #feb800;
      color: #ffffff;
    }
    #navbar li:hover a {
      color: #ffffff;
    }
    

    And background for span should not be that general, as it will affect all spans on page.