Friday, January 29, 2010

CSS Positioning Revisited

A CSS element is the basis of document structure. CSS positioning properties provide for the positioning of an element.

There are four positioning methods:
  • Absolute - element is positioned relative to the first parent element
  • Fixed - element is positioned relative to the browser window
  • Relative - element is positioned relative to its normal position
  • Static - element is positioned in its default location

This syntax declares a style applicable to the element with ID pushdown that causes the element to be rendered 100 pixels from the top of its immediate parent:

<style type="text/css">
#pushdown { position:absolute; top:100px; }
</style>
This syntax declares a style called fixedPosition, applicable only to the <p> tag, that causes the element to be rendered 10 pixels from the top of the browser window:

<style type="text/css">
p.fixedPosition { position:fixed; top:10px; }
</style>
This syntax declares a style called moveRight, applicable only to the <h2> tag, that causes the element to be rendered 20 pixels to the right of the location at which it would have otherwise been presented:

<style type="text/css">
h2.moveRight { position:relative; left:20px; }
</style>
This snippet demonstrates the explicit use of position:static, which is normally the default, to override an existing global <h2> style:

<html>
<head>
<style type="text/css">
h2
{
position:relative;
left:20px;
}
h2.static
{
position:static;
}
</style>
</head>
<body>
<h2>Appears 20px the right</h2>
<h2 class="static">Overrides h2 style</h2>
</body>
</html>