floatitis pt3
The third part of the floatitis series will again focus on a way to avoid abusing floats (and avoid having to worry about parents elements wrapping correctly). After taking a closer look at the css text align property for positioning simple inline snippets of content, next up is a combination of floating and margin trickery to do the job. Even though it still (quite obviously) involves floating, it will eliminate the need to clear the parent container.
how it works
.caption {width:8em; float:left;} .detail {margin-left:9em;}
Floating an element causes sibling content to wrap around it. This is nice for images and text, but not always the wanted behavior, especially not when dealing with separate (parts of) components. So what we want to do is mimic the behavior of two floating elements without actually floating the both of them. The solution is simple.
A mere margin on the siblings, spanning the width of the floated element, suffices. When the first element is floated, the siblings can be given a margin in the same direction so they'll both align on the same horizontal rule. This way, the siblings don't have to be floated and the container will nicely wrap around the content of the siblings.
when to use
This methods has several limitations and drawbacks. First of all, the floated element should be given a width of which the margin on the siblings is derived. This means adapting two or more values to create one single effect, not something I usually prefer to do. Also, you must be certain that the height of the second element will be bigger than that of the floated element, or else you'll still run into problems with the floated element breaking from its container. Finally, there's no playing with source order here, the floated element should be first in source, otherwise this method won't work.
This method is best used when the content of the first element is predictable in height and limited in width. You might recall the article I've written on the caption-detail structure, which is a perfect example for using the margin/float method as the caption element is small and predictable in size. The detail content is typically larger, so no wrapping problems will arise. Another typical example is aligning form labels and form inputs.
conclusion
Again a method that is bound to a few limitations, but has definite added value in most projects. Even though it still requires floating, it eliminates the need for clearing the parent and is pretty compatible cross-browser (no more irritating double margin bugs in ie6). No miracle cure, just another method for positioning elements which can make life a little easier when used in the right circumstances.