Learn How To Center A Navbar


In this article, you will learn How to Center A Navbar in HTML & CSS.

What is a Navbar?

A Navbar is a section in a Website that contains links to other parts of the Website for example About Page, Contact Page, Feedback Page, etc.

Let’s create a Navbar in HTML:-

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="style.css" rel="stylesheet" />
    <title>Center Navbar</title>
  </head>
  <body>
    <nav>
      <ul class="nav-cont">
        <li class="nav-item"><a href="/">Home</a></li>
        <li class="nav-item"><a href="/products">Products</a></li>
        <li class="nav-item"><a href="/about">About</a></li>
        <li class="nav-item"><a href="/contact">Contact</a></li>
      </ul>
    </nav>
  </body>
</html>

In the above code we have a list of Navigation items with nested <a> tag so that we can navigate to different parts of our Website. And classes to design it in our CSS file.

Styling The Navbar:-

style.css

.nav-cont {
  display: flex;
  list-style-type: none;
  justify-content: center;
  flex-wrap: wrap;
  background-color: #ff7675;
}
.nav-item {
  padding: 1em;
}

In the above code we have added some styles to our <ul> with class of nav-cont.

Each line of code represents:-

  • display:flex; : it expands the item to display Horizontally(in our case) or Vertically.
  • list-style-type:none; : to remove the list icon (like square, circle).
  • justify-content:center; : to center the whole navbar.
  • flex-wrap:wrap;: for the responsiveness of the website (for different screen sizes) as it will adjust automatically & wouldn’t overflow.
  • padding:1em; : to add some space between different items.

Result of the above code:-

Center A Navbar

Share on social media

//