2009
02.23

While the title mentions centered floats, the solution that I am about to present does not use floats at all but the end result is the same. Floats are notorious for their browser compatibilities and quirkiness. Through the years, there are only a few elegant solutions on float related problems. One notable solution is the use of hasLayout and the overflow property to clear floats which worked for all major browsers.

I have tried to tackle the centered floats problem a few times without much success, usually giving up and relying on methods that counter-position the container from it’s parent. It is not until I came across the Mozilla Webdev post on how to create a cross-browser inline block which reminded me of the reason why it’s so hard to create centered float is because we lacked the ability to define a cross-browser inline block. With that ability, we can just use text-align: center to do the job as what it would have done to images.

Now, let us jump directly into the CSS.

li {
	/* you can set a height or width if you need to */
 
	display: inline-block; /* for modern browsers */	
	display: -moz-inline-stack; /* for FF 2 */
	zoom: 1; /* for IE, triggers hasLayout */
	*display: inline; /* IE 7 and below */
 
	background:#CCC; /* not needed */
	margin: 5px; /* not needed */
}
 
ul {
	text-align:center; /* aligns all the children to center */
 
	background:#999; /* not needed */
	margin: 0; /* not needed */
	padding: 0; /* not needed */
}

Here is the html.

<ul>
    <li>aeroplane</li>
    <li>bird</li>
    <li>cat</li>
    <li>dog</li>
    <li>elephant</li>
    <li>fish</li>
</ul>

And the code in action.

aeroplanebirdcatdogelephantfish

4 comments so far

Add Your Comment
  1. Nice one. You don’t need the * in front of the display for ie5.5+. Just put !important after the -moz-inline-stack to make the margin work in FF2 and below. You can also use -moz-inline-box which is pretty much the same thing as stack.

  2. Thanks a ton for putting this up, you just solved a problem I have been trying to solve for over a week now!

  3. @Siddhartha NP
    @Ryan I updated the CSS code without using the !important tag. Check it out.

  4. Kean, what update are you referring to? It seems that what Ryan mentioned (*display) is still there.