CSS Horizontal Navbar

A horizontal navigation bar arranges its links in a single row across the top of the page, the most common site header pattern.

A horizontal navbar begins as the same list of links as a vertical one; the difference is how you lay the items out in a row. Flexbox is the modern way to do this, though inline-block also works.

Laying links out with Flexbox

A flex navbar

<!DOCTYPE html>
<html>
<head>
<style>
nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 8px;
}
</style>
</head>
<body>

<nav>
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>

</body>
</html>

display: flex turns the list items into a row, and gap adds even spacing between them without needing margins on each item.

Two ways to build the row

MethodNotes
display: flexPreferred today; gap for spacing, easy alignment
display: inline-blockOlder approach; watch for whitespace gaps between items
float: leftLegacy; needs a clearfix on the parent

Styling the links

Padded, clickable links

<!DOCTYPE html>
<html>
<head>
<style>
nav {
  background: #00643c;
  display: flex;
}

nav a {
  display: block;
  padding: 14px 18px;
  color: #fff;
  text-decoration: none;
}

nav a:hover {
  background: #00502f;
}
</style>
</head>
<body>

<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Contact</a>
</nav>

</body>
</html>
Note: To push some links to the far right, such as a login button, wrap them in a group and use margin-left: auto on it inside the flex container.

Push a link to the right

<!DOCTYPE html>
<html>
<head>
<style>
nav {
  display: flex;
}

nav .login {
  margin-left: auto;
}
</style>
</head>
<body>

<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#" class="login">Log in</a>
</nav>

</body>
</html>

Exercise: CSS Navigation Bars

What HTML element is most commonly used as the base for a navigation bar's links?