CSS Layout and Positioning Techniques

Newbies tend to gravitate towards absolute and relative positioning because they give more of an illusion of control over how browsers render pages than floats and margins do and they are conceptually easier to understand.

Below are links to the best resources that I've come across on these topics.

Floats and Margins

Clearing and Containing Floats

To force one element to appear below (or after) a float, it is often necessary to clear a floated element. You can clear left floated elements, right floated elements, or both.

Also when you want to make a non-floated container fully contain a floated element, you need some method to make the bottom edge of the container extend past the bottom of its floated descendants. Not every way of doing that requires the use of the clear property. Some methods are better than others.

The easiest, though not always suitable, way to make an element contain any floated descendants is to float it. A floated element automatically contains any floated descendants. When floating the parent element isn't practical, the PIE/Aslett approach is best, because it doesn't require adding extra markup and is more robust than using the overflow property. It's listed as option 2 in the first link below.

Collapsing Margins

Basically, elements that are set to display:block; either by default or explicitly, are not floated, and are not absolutely or relatively positioned will have their vertical (top and bottom) margins collapse with an adjacent vertical margin if no padding or border gets in the way. The collapsed margin will be the greatest of the margins being collapsed. For example, when you have a <p>, <ul>, <ol>, or header (<h#>) that isn't floated or positioned and that has a top margin inside a <div> that doesn't have any top padding or a top border, the margins will collapse resulting in the <div> being pushed down.

Absolute and Relative Positioning
and Stacking Contexts

Absolutely positioned elements are positioned based on the position of the nearest positioned ancestor (an element with its position property set to a valid value other than static, which is default) or, if there is none, <html>.

Relatively positioned elements are visually shifted relative to where the element would be positioned otherwise, but their normal position is still occupied as if they were not relatively positioned.

More on Positioning and Layout Techniques

Completed Layouts

Related Links:

Last update: 2010-09-20