Saturday, December 22, 2007

Not much to Gloat about Floats

Well, here comes another of my quick but crazy posts (technical you see :D..). I happened to spend some time yesterday trying to figure out a particular way of rendering a HTML page when I observed that some part of the text was truncated across pages when printed. That was when this post originated. After spending hours on the issue, the samaritan I am, I decided that nobody's time is worth spending on figuring out this issue. Though initially very obscure, the culprit was "Float".

I wouldn't have imagined in my wildest dreams that such an innocuous CSS element could be such a potential blockhead. Now that I had promised to keep my post really short, let me try to put this in the most straight forward terms..

Float : is a CSS property of any object ( that can be set to "left", "right", "inherit" or "none".

Purpose : Initially created for placing text or images within a container. But this usage can even be extended to other container elements like DIV, SPAN etc..

Usages : object {

(DiV1) (span1 style="float:left")




Common Pitfalls:

* The most common mistake that we commit is not providing sufficient place for the element which we are floating. So if we have absolute specifics like width etc., we have to ensure that there is sufficient amount of space for the float to render. If not the browser dutifully renders it at the next line where sufficient space would be available.

* A good thing that you should always do while floating containers is to specify where the next element should render. For example in the above case, we have said what should be done with span but nothing about span2. Hence the browser would again take charge and render it as close as possible to span1, which is again a potential screw up. So having a "clear:right" would have been the ideal thing to do here.

* Contents of float element can overlap, hence all the inline entities should be placed after the floated element.

As a parting note, you might also want to specify the overflow of the container elements to prevent any visual mishaps. Float property has many peculiarities across various browsers and wouldn't be an advisable option to scatter it ruthlessly across pages. Moreover, the issues caused by floats aren't readily debugg'able. Beware guys ! stay limited with the usage of floats..

No comments: