LAST UPDATED: AUGUST 5, 2021
How to center navbar with CSS?
The navbar is used to navigate to the pages on the website. It contains the links to the pages. The navbar can be aligned to the center, left, or right using CSS properties. Here, we will learn how to center the navbar.
Center the navbar
We can center the navbar using margin: auto
property. It will create equal space to the left and right to align the navbar to the center horizontally. Additionally, add the width
of the navbar.
Example: Centering the navbar with CSS.
Here, we have added <a>
elements inside the <div> tag to create the navbar. And centered it with margin:auto
class.
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML </title>
<style>
/* Add a black background color to the top navigation */
.navbar {
background-color: #CCCCCC;
overflow: hidden;
width: 700px;
margin: auto;
}
/* Style the links inside the navigation bar */
.navbar a {
float: left;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 20px;
}
h2 {
text-align: center;
}
</style>
</head>
<body>
<div class="navbar">
<a class="active" href="#">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
<h2> Here we have successfully centered a navbar </h2>
</body>
</html>
Output
Here is the output of the above program.
Example: Center the nav with CSS
We can set the width of the navbar so that the navbar centers at a particular viewport width.
Conclusion
In this tutorial, we have learned to center the navbar with CSS. We used the margin: auto
property to center the navbar. See the examples to know more about the code.