Center a Simple CSS Horizontal Navigation Bar Made by Using Float

Chun Ming Wang
2 min readMay 17, 2019

--

For HTML code please see this article. The CSS code is

* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
background-color: #ccc;
}
nav ul {
list-style: none;
padding: 0;
margin: 0;
background-color: #444;
text-align: center; /* step 4*/
overflow: auto; /* step 5*/
}
nav li {
float: left; /* step 1 */
width: 20%; /* step 3*/
}
nav a {
display: block; /* step 2 */
}
/* common text style */
nav a {
font-family: sans-serif;
font-size: 1.2rem;
height: 3rem; /* vertically center */
line-height: 3rem; /* vertically center */
color: #fff;
text-decoration: none; /* remove underline */
}
nav a:hover {
background-color: #005f5f;
}
nav a.active {
background-color: #eee;
color: #444;
cursor: default;
}

Step 1: float all <li> in the <ul>. Notice that the width of the <ul> now becomes zero. That is the parent element of the <li> collapses upon itself. See this explanation for detail.

Step 2: set display: block for every <a> element. Therefore I can set padding and margin for <a>. This also make <a> take up all available space of the containing element (i.e., <li>).

Step 3: set width for all <a>. There are five links. Each link takes up 20% of the parent width. 5 x 20% = 100%.

Step 4: center the link’s text horizontally.

Step 5: make the <ul>contain” the floated element. An critical line. Read this article for detail. In short, setting overflow: auto to parent element will force the parent element to contain the children elements.

Now the menu is done.

To center this navigation bar is easy. Simply add the following code to the end of the CSS file

nav {
width: 80%;
margin: 0 auto;
}

This code set width to <nav> and center it horizontally.

--

--