No Time Dad

A blog about web development written by a busy dad

CSS Full Width li Links

A pattern for building side navigation menus I use regularly is to create a nav element with an ol (ordered list) containing each link as li (list item) elements. I always remove the styling from the ol element, as it’s not needed for side navigations.

I think it’s a good idea to let the user know which page they’re currently viewing, and which link they might be hovering on. The latter might be overkill, but I think it’s a nice touch. The navigation looks something like the below, with the corresponding html and css beneath it.

<nav>
  <ol>
    <li><a class="nav_item active" href="#1">Link 1</a></li>
    <li><a class="nav_item" href="#2">Link 2</a></li>
    <li><a class="nav_item" href="#3">Link 3</a></li>
  </ol>
</nav>
ol {
  margin: 0;
  list-style: none;
}

.nav_item:hover {
  background-color: deepskyblue;
}

.active {
  background-color: deeppink;
}

In the example above, the nav_item background-color is the length of the text instead of the entire width of the li element. The reason this happens is because the li element comes with the default display property value of list-item. This value prevents the contents of the list item element to take up the entire width.

An easy way to fix this and create a full width li link is to convert the a element to a flexbox container. This is done by adding display flex to the nav_item selector. The html is the same as shown above, but the css changes slightly as shown below.

ol {
  margin: 0;
  list-style: none;
}

.nav_item {
  /* Initialize a flexbox container so the li element contents will fill available space */
  display: flex;
}

.nav_item:hover {
  background-color: deepskyblue;
}

.active {
  background-color: deeppink;
}
<nav>
  <ol>
    <li><a class="nav_item active" href="#1">Link 1</a></li>
    <li><a class="nav_item" href="#2">Link 2</a></li>
    <li><a class="nav_item" href="#3">Link 3</a></li>
  </ol>
</nav>

An added benefit of this approach is that since the a element is a flexbox container, we have access to all of the helpful flexbox properties like align-items and justify-content. These are expecially helpful if there is an icon in the nav link. Or for ensuring the spacing is even.