
In a previous article, we briefly went over CSS Floats. However, they deserve a more in-depth look, as they can be useful (and sometimes tricky).
CSS Floats allow you to position an object to the left or right, and have another object directly opposite (horizontally, speaking) it (on the same imaginary “top line”). We can use the floats using the float property in CSS. Let’s have a look at some example markup to apply this property to.
[html]<div id="left"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac dui erat. Vivamus dui neque, laoreet volutpat tempor vel, facilisis eget tortor. Proin imperdiet mi non enim consequat tristique.</p></div>
<div id="right"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac dui erat. Vivamus dui neque, laoreet volutpat tempor vel, facilisis eget tortor. Proin imperdiet mi non enim consequat tristique.</p></div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac dui erat. Vivamus dui neque, laoreet volutpat tempor vel, facilisis eget tortor. Proin imperdiet mi non enim consequat tristique.</p>[/html]
Now, say we want to position the first div to the left, the second to the right and the third underneath. We would do something like this (you’d have to play with the widths of the floated divs):
[css]#left {
float: left;
}
#right {
float: right;
}[/css]
Which is great, #left will be on the left and #right will be on the right. However, you may encounter a problem with the content thats below these float divs. Content below the floated objects may wrap onto the floated object’s line, creating an unsightly result.
To resolve this we will add the following markup after our floated divs:
[html]<div class="clear"></div>[/html]
Then, in our CSS:
[css].clear {
clear: both;
}[/css]
CSS floats are a useful feature when coding designs and wrapping text around images (just use one float, and no “clear”). While they can sometimes be a bit tricky, it’s usually a simple fix and the pros outweigh the cons.
