I have two answers for you.
If you want to stick with the float
model:
Your ul
element needs to have the overflow property set (without this property, your ul
(or any element containing floated elements) is not given a height (this is expected behavior, mind you: http://www.quirksmode.org/css/clearing.html) and will therefore default to a height of 0 - the effect of this will be that if you set different background colors for your ul
/li
and body, the background of your ul
will not seem to display).
ul {
text-align: center;
width: 300px;
overflow: auto;
}
Your li
elements need to have widths set, otherwise - as floated elements - their width will be set to whatever they contain. I've used pixels, below, but you can use a percentage value too.
li {
float: left;
margin: 5px 0 5px 0;
width: 100px;
text-align: center;
}
Use the display:inline-block
property for your li elements (if support for old browsers isn't a priority). IE 7 does not support this, so it's not useful if you need wide cross-browser support, but it creates the effect you want - though make sure you then delete any spaces between your </li>
and <li>
tags, otherwise they will be counted in the overall width and will show up as spaces between the elements.
One advantage that this method has is that you don't have to know or set the width of the container ul
if you use percentage widths on your contained li
elements, you still get the centering for free with the text-align property you already have. This makes your layout very responsive.
Here's markup and CSS that works the way I think you are requesting:
Markup:
<ul>
<li>banana</li><li>orange</li><li>apple</li>
</ul>
CSS:
li {
display:inline-block;
margin:5px 0 5px 0;
width:33.33%;
}
ul {
text-align: center;
}
- If you'd rather keep the markup on multiple lines, then you'll have to fiddle with the left and right margins of your
li
elements in the CSS.
- If you add
li
elements, you'll have to change the percentage width to match (for example, with four li
elements in your markup, you'd need to change your CSS to have a width of 25% for each one).
nav
display: table
, theul
display:table-row
and theli
display:table-cell
, then it all worked amazingly well. – Courtenay