Thursday, September 24, 2009

CSS: Why Use Relative Positioning?

The CSS position can have 4 values: static (the default), relative, absolute, or fixed. IE6 doesn't support fixed positioning, so that leaves you with 3 values. Static positioning leaves elements in the normal flow, so you are left with 2 really interesting values:

  • relative – Leaves the element in the normal flow, but allows you to move it relative to that position using top and left.
  • absolute – Takes the element out of the normal flow, and positions it relative to the top left corner of its closes positioned ancestor, i.e. the closest ancestor with a position set to relative or absolute (or fixed).
With this in mind, there are 2 main reasons to use a relative positioning:
  • Obviously, you might want to move an element relative its positioning in the normal flow. So you would use position: relative in conjunction with a top and left on an element. But in my experience, this is rarely needed.
  • More often, you want to position an inner box relative to an outer box. You do so by using position: relative on the outer box and position: absolute on the inner one, for instance to produce the result shown below, with the corresponding HTML immediately following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style type="text/css">
.outer { position: relative;
border: 2px solid #999; }
.inner { position: absolute; top: 1em; left: 1em;
border: 2px solid #666; }
</style>
</head>
<body>
Outside outer
<div class="outer">
Outer
<div class="inner">Inner</div>
</div>
</body>
</html>
If you were to ignore the position: relative on the outer element, you would get: