May 5, 2012

Aligning two lines of horizontal links evenly with CSS

Question by Derrick

I have 6 links, all different character lengths on two lines. I need everything to align evenly. Like this:

Home       About Us     Location
Contact    Visit        Schedule

I imagine the way to do this is to make the li a specific width and then apply an appropriate margin to the right side, but for some reason I can’t apply a width. If I have the following html skeleton, how would I edit the CSS to accomplish this? I’ve looked around the web for a solution, but I’ve haven’t found any similar questions because my menu sits on two separate lines.

<div class="footer">
 <ul id="footerlinks">
  <li><a href="link 1">Home</a></li>
  <li><a href="link 2">About Us </a></li>
  <li><a href="link 3">Location</a></li>
<br>
  <li><a href="link4">Contact</a></li>
  <li><a href="link5">Visit</a></li>
  <li><a href="link6">Schedule</a></li>
</ul>

Answer by Starx

Fix the width of <ul> and <li>. And remove the <br /> it makes the markup invalid.

HTML

<ul id="footerlinks">
  <li><a href="link 1">Home</a></li>
  <li><a href="link 2">About Us </a></li>
  <li><a href="link 3">Location</a></li>
  <li><a href="link4">Contact</a></li>
  <li><a href="link5">Visit</a></li>
  <li><a href="link6">Schedule</a></li>
</ul>

CSS

#footerlinks { width: 300px; }
#footerlinks li { width: 100px; display: inline-block; }

Demo

Demo(with white-space fix)

...

Please fill the form - I will response as fast as I can!