Sometimes there are things you want to do in your layouts with CSS (Cascading Style Sheets) that you assume would be easy, but as you dive into the coding, it turns out what you thought should work just isn't cutting it. Equally spacing elements across a horizontal area so that the first and last items are flush with the left and right borders respectively turns out to be a perfect example of this. For the lowdown on how to best accomplish this, read on!

Why Isn't This Working?!?!

Here's the issue I found myself running into on more than one occasion:

I need to display an array of items, such as in a catalog or members directory, and I want to span them horizontally across the available space. My knee-jerk reaction always seems to be to float each element's container. Now for some applications this is fine, but when it comes down to pixel perfect layout mo-jo, it has a few downsides:

  1. If the elements are not all of equal height (as is often the case with dynamic content), then odd "stacking" will eventual happen on multiple rows, when an item in the previous line has more height then other items in the same row, and the next row can't slide all the way over to the left.
  2. Even if we programmatically add in a clearing element after the last item in a row or force a conformed height to all elements, we have to accept that the last item won't arrive flush to the right border of the containing element because of the right margin applied to the elements to space them apart. (We could change the right border on the last item of every row, but then we still have to deal with responsive widths... another can of worms!)

At first glance it seems like there should be an easy way to just apply percentage based widths and border to our elements and be done with it, but as we soon discover... using floats just doesn't give us that perfect spread from left to right with our elements flush to the parent element's borders.

Aha!!! It's So Simple!

So what's the solution?? It's a thing of facepalm inducing simplicity. Instead of using float:left;, we simply give the parent container the text-align:justified; CSS rule and the elements themselves the display:inline-block; rule, along with a little trick that ensures that the justification works even on a single row.

Yep, that's it. Have a look:

<ul id="parent">
  <li>element 1</li>
  <li>element 2</li>
  <li>element 3</li>
  <li>element 4</li>
#parent {
  text-align: justify;
  font-size: 0.1px; /* IE 9/10 fix */
#parent li {
  display: inline-block;
#parent:after {
  content: '';
  width: 100%; /* Ensures justification for single lines */
  display: inline-block;

Thanks to Chris Again!

Once again a great solution came from a great CSS techniques source, Chris Coyer. Kudos to you Chris, and Happy coding!