CSS development is a hard land where you have to struggle with many browser incompatibilities and not so easy to use structures. Here are two extremely useful techniques that allow you to get around common float problems.
List of items without floats
Problem
It is common to display a list of items that flow horizontally. Common examples are tabs or cloud tags. A common way to write it is to use the float property.
<style> li { float: left; } </style> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> |
However, you are going to struggle with the way floating elements flow in the document. You have to clear them, you will have strange behaviors with multiple floats ...
Technique
There is a better way to do it: display: inline-block;
. The element will behave inline (as a span) when being positioned in the flow and as a block when styling it. Exactly what you want.
The code is nearly the same, but the float is now gone!
<style> li { display: inline-block; } </style> <ul> <li>One</li> <li>Two</li> <li>Three</li> </ul> |
However, this code does not work in ie7 (and of course ie6). But ... There is a simple trick to make it work! Every time you do a display: inline-block
, just add the two associated lines. The magic is explained by Ryan Doherty from Mozilla.
li { display: inline-block; /* The following 2 lines do the magic */ zoom: 1; *display: inline; } |
You can read more about the zoom property and its strangeness on the On Having Layout article.
Benefits
- No more floats and all the problems involved
- Cross browser (even ie6)
- You can now center elements using
text-align
Demo
- One
- Two
- Three
- Four
- Five
No more clear
to get around floating elements
Problem
When working with floating elements, you are probably going to do something like this:
<div> <div style="float: left;">Left Menu</div> <div style="float: left;">Another Menu</div> <div style="float: right;">Content</div> <br style="clear: both;" /> </div> |
The problem is you have to use a <br />
which takes vertical space, completely destroy your padding/margin organization ...
Technique
There is one easy technique described by PPK that is solving all the problems and has no side effect!
<div style="width: 100%; overflow: auto;"> <div style="float: left;">Left Menu</div> <div style="float: left;">Another Menu</div> <div style="float: right;">Content</div> </div> |
The trick is to add width: 100%; overflow: auto;
to the parent box and it just works! The parent box now wraps around all the floating elements and you can properly style it. It works will all browsers, even with ie6.