Oct 7, 2009

Centering floated elements with CSS

Today I found a tricky way to get floated elements centered into a container div. The idea is pretty basic and it doesn't use any CSS hack. So, let's comment first about the problem. I have a variable number of floated elements which I want to display centered if they don't fulfill the container div.
My first approach was to wrap them with another div, which I will call container, where I can use the margin: auto property. In order to get the contained floated elements centered I will need to specify a width for the container. This option is not good, and I hate to declare width into a div. So, I start to research and to do some test and finally I get a very simple solution.
So, the main idea is to use float and relative positioning to achieve the goal. Let me explain it with more details.
I said I have some floated elements into a div, I'm going to use 3 for this example.

<style>
.clear {float: none; clear: both;}

.item {float: left;}
</style>

<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="clear">

First, I need a container for these elements in order to get them centered into it.


<style>
.clear {float: none; clear: both;}

.item {float: left;}
</style>

<div class="container">
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="clear">
</div>

And now let's start to work. As I said, I used float and relative positioning to achieve this. So, the main idea is to apply relative positioning over the container and set the left property to 50%. This will put our container starting in the middle of the screen. Then I apply float to get the width of my container stretched into it content.

<style>
.clear {float: none; clear: both;}
.container {float: left; position: relative; left: 50%;}
.item {float: left;}
</style>

<div class="container">
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="clear">
</div>

Now is where the magic begins! So far I have my floated elements in the middle of the viewport, but not centered. Ok, now you just need to add relative positioning to floated elements and set the right to 50%. And voilá!

<style>
.clear {float: none; clear: both;}
.container {float: left; position: relative; left: 50%;}
.item {float: left; position: relative; right: 50%;}
</style>

<div class="container">
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="item">Lorem Ipsum</div>
<div class="clear">
</div>

Check it! You can inspect the content below with firebug! I have added some border color in order to give you a clear way of where is every div. Blue one is the container, red ones are the floated elements.


Lorem Ipsum
Lorem Ipsum
Lorem Ipsum



Hope you can got it! Any doubts just ping me!