Floats, the nightmare of everyone starting out with css. Sure they are helpful, but are they worth all the bugs and cursing and exceptions on exceptions on rules? The next couple of articles will take a closer look at floats, giving a small introduction on their nature and elaborating on methods to avoid using floats. This way you can hopefully ignore a whole lot of potential future bugs and browser fixes.
Floats have been around for a while, and were constructed to fix a rather specific problem. Even though today we're using them for all kinds of tricks, you could say that most of the time we're actually abusing the float property.
Initially the float was designed to allow for text to wrap around images. The image would be floated and the text would flow around the image, creating a typical magazine style layout, something not possible before. Since those days layouts on the web have become a lot more complex and the float has played a major role in the switch from table layout to div layout. Sadly, this was not foreseen when the float was conceived, which brought up a lot of problems with its standard behavior.
The float property has some irritating side effects. Most importantly, a floated element is taken outside the flow of the document, meaning that its parent container has no notion of the floated elements inside it. If the floated element is larger than the non-floated content inside the parent, it will simply flow outside its parent, usually screwing up your delicately constructed layout.
A very common issue (though prescribed behavior) which has various fixes. The most popular one being the clearfix class which should be added to each parent with floated children (if you want to play it safe). It's a pretty ugly class/fix but necessary to keep most of our layouts in place.
Other problems with floats revolve around bugs present in ie6 (3px jog and double margin bug are two common ones), its behavior concerning collapsing margins and the battle of floats that don't have enough space to fit together on one horizontal line. If you've ever designed a css site, you probably know all too well what I'm talking about.
The bottom line is simple, floats are extremely helpful in creating our css designs, but they are also a trap for unexpected bugs and unwanted layout behavior.
Luckily there are alternative methods to avoid the overuse of floats (or at least for better protection against its negative side effects). The upcoming articles will go into more detail about these methods, but to give you a little taste of what's to come, here's a short list of topics I'll be going through.
- text-align:right saves the day
- the margin/float combo
- the use of position:absolute in controlled circumstances
- the futuristic display:inline-block
Hopefully at the end of this series you'll have a broader palette of options to construct your layout in css, with a minimal chance for unexpected bugs and broken layouts.