Friday, May 1, 2009

Floating elements

When moving from tables based layout to div based layouts, the first things people struggle to understand is how to use div elements. The very first thing that comes to the mind is to make div elements display in an inline fashion. There is a different tag for such things, called span. It is therefore not a good idea to make div tags inline display elements. Rather, there is a whole new alternative to float elements around.
Floating is a concept of making elements flying around the web page, constrained to the space provided by their parent elements. The general trick used are to float the elements left, or right. When an element is asked to float right, it tries to fly to the maximum position it can reach to it's right, without being blocked by any other elements that may be in it's path. This comes handy when we need to split pages to form skeletal structures.

The simplest form of a float trick, involves 2 steps.
  • Define the width of the element.
  • Float it "right", or "left".
Lets consider a problem to better explain this. Assume that we need to create a page that has 2 columns, and boxes inside each column that position themselves one below the other. Each box's height does not depend upon any of the boxes in the nearby column.

CSS code

HTML code

Sample output


There is a small problem however with this approach. Elements containing floating children don't consider the height of their children. It is therefore required to "clear" both sides at the end of all the child elements.

0 comments:

Post a Comment