How do I justify a horizontal list?
Modern Approach - CSS3 Flexboxes
Now that we have CSS3 flexboxes, you no longer need to resort to tricks and workarounds in order to make this work. Fortunately, browser support has come a long way, and most of us can start using flexboxes.
Just set the parent element's display
to flex
and then change the justify-content
property to either space-between
or space-around
in order to add space between/around the children flexbox items. Then add additional vendor prefixes for more browser support.
Using justify-content: space-between
- (example here):
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-between;
}
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Contact Longer Link</li>
<li>Contact</li>
</ul>
Using justify-content: space-around
- (example here):
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-around;
}
<ul class="menu">
<li>About</li>
<li>Contact</li>
<li>Contact Longer Link</li>
<li>Contact</li>
</ul>
You need to use a "trick" to make this work.
See: http://jsfiddle.net/2kRJv/
HTML:
<ul id="Navigation">
<li><a href="About.html">About</a></li>
<li><a href="Contact.html">Contact</a></li>
<!-- ... -->
<li class="stretch"></li>
</ul>
CSS:
#Navigation
{
list-style-type: none;
text-align: justify;
height: 21px;
background: #ccc
}
#Navigation li
{
display: inline
}
#Navigation .stretch {
display: inline-block;
width: 100%;
/* if you need IE6/7 support */
*display: inline;
zoom: 1
}
Details on IE6/7 trickery: Inline block doesn't work in internet explorer 7, 6
This can also be achieved using a pseudo element on the ul
element:
ul {
margin: 0;
padding: 0;
list-style-type: none;
text-align: justify;
}
ul:after {
content: "";
width: 100%;
display: inline-block;
}
li {
display: inline;
}
Just do:
ul { width:100%; }
ul li {
display:table-cell;
width:1%;
}