How do I justify a horizontal list?

Maxpm picture Maxpm · Jul 30, 2011 · Viewed 75.7k times · Source

I have a horizontal navbar like the following:

<ul id = "Navigation">
    <li><a href = "About.html">About</a></li>
    <li><a href = "Contact.html">Contact</a></li>
    <!-- ... -->
</ul>

I use CSS to remove the bullet points and make it horizontal.

#Navigation li
{
    list-style-type: none;
    display: inline;
}

I'm trying to justify the text so each link is spread out evenly to fill up the entirety of the ul's space. I tried adding text: justify to both the li and ul selectors, but they're still left-aligned.

#Navigation
{
    text-align: justify;
}

#Navigation li
{
    list-style-type: none;
    display: inline;
    text-align: justify;
}

This is strange, because if I use text-align: right, it behaves as expected.

How do I spread out the links evenly?

Answer

thirtydot picture thirtydot · Jul 30, 2011

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