Justified navigation bar
suggest changeThe horizontally justified navigation (menu) bar has some number of items that should be justified. The first (left) item has no left margin within the container, the last (right) item has no right margin within the container. The distance between items is equal, independent of each item’s width.
HTML
<nav>
<ul>
<li>abc</li>
<li>abcdefghijkl</li>
<li>abcdef</li>
</ul>
</nav>
CSS
nav {
width: 100%;
line-height: 1.4em;
}
ul {
list-style: none;
display: block;
width: 100%;
margin: 0;
padding: 0;
text-align: justify;
margin-bottom: -1.4em;
}
ul:after {
content: "";
display: inline-block;
width: 100%;
}
li {
display: inline-block;
}
Notes
- The
nav,ulandlitags were chosen for their semantic meaning of ‘a list of navigation (menu) items’. Other tags may also be used of course. - The
:afterpseudo-element causes an extra ‘line’ in theuland thus an extra, empty height of this block, pushing other content down. This is solved by the negativemargin-bottom, which has to have the same magnitude as theline-height(but negative). - If the page becomes too narrow for all the items to fit, extra items wrap onto the next line and that line is justified as well. The menu grows taller as needed. In a right-to-left page, the items align from the right.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents