How do I distribute items horizontally with CSS?
You can do what you are after using inline-block
, pseudo-elements and text-align: justify;
, but it will only work in IE8 and above.
Here is the code:
<!-- HTML -->
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li>List Item 4</li>
</ul>
/* CSS */
ul {
text-align: justify;
}
ul:after {
content: '';
display: inline-block;
width: 100%;
}
ul:before {
content: '';
display: block;
margin-top: -1.25em;
}
li {
display: inline-block;
margin-right: -.25em;
position: relative;
top: 1.25em;
}
Live demo: http://jsfiddle.net/joshnh/UX9GU/
As an addition to joshnh answer, if anyone has the same issue:
Watch out: text-align: justify;
needs a space after every display: inline-block;
element to work. Otherwise the elements are treated as one word and will not distribute horizontally.
So this won't work:
<!-- HTML -->
<ul><li>Item 1<li><li>Item 2<li><li>Item 3<li><li>Item 4<li></ul>
But this will:
<!-- HTML -->
<ul>
<li>Item 1<li>
<li>Item 2<li>
<li>Item 3<li>
<li>Item 4<li>
</ul>
I just had this issue because we are minifying our HTML-Markup and the minifier puts everything in one line.
There is an clean solution:
http://radiatingstar.com/distribute-divs-images-equaly-line
#container {
text-align: justify;
}
#container > div {
width: 100px; /* Declare your value. Can be in relative units. */
display: inline-block;
vertical-align: top;
}
#container:after {
content: "";
width: 100%;
display: inline-block;
}