Center the UL Tag with Floated LI Element - Quick Tip

Hey all! Today I’m gonna give a little quick tip that I find myself sharing a bit with my fellow developers. Some times we need to center an unordered list that has floated _LI _elements inside. I’ll show you the code I use to center this UL tag and clear all the floats in side so the UL.

 

Step 1 - Center the UL!

First off, here’s our HTML code.

<ul id="navigation" class="group">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Portfolio</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">Contact</a></li>
</ul>
So we have our _Unordered List_ with an ID of _navigation_ and a class called _group_. This is what my HTML generally looks like for my navigation on my sites usually. NOW, we need to add some CSS to make this thing work right. Add the following CSS to your stylesheet.
#navigation { 
   /* Reset the default UL styling */
   margin:0;
   padding:0;
   list-style:none;
   background:none;

   /* center the UL */
   display:inline-block; 
   zoom:1;  /* IE fix */
   *display:inline;
}

#navigation li {
   float:left;
   margin:0 5px; /* add some spacing to the LI's */
}
The lines of CSS here will float all your _LI_'s next to each other and add some spacing, and will center your navigation to the parent element. Now you are probably satisfied here, but there's one more step we need to make before we call it quits! ## Step 2 - ??? This is a step that is normally overlooked because to the untrained eye, everything is peachy. But if we were to inspect element we'll find that the _UL_ tag has no height! This is more clear when you have a background color or image set to the parent element. The since we floated the _LI_'s we pull them from the document flow causing the parent div to collapse. We use what is known as the "clearfix". I like to rename this to group instead of adding the words clearfix to my code. So that's the class I have chosen below. Just add this to your stylesheet, and by adding the class to the parent element you'll always clear floated elements instead of adding an empty div tag. _How neat! ;)_
.group:before, .group:after, footer:after, .post:after { content:""; display:table; }
.group:after { clear:both; }
.group { zoom:1; }

Step 3 - Profit and rejoice!

And now you can get on to bigger better things :) If you have any ideas about optimizing this or if you have an alternative trick let me know!