Webbits

Grokking CSS positioning

This page covers how position works in CSS 2.1. The next page talks about how you could use the possibilities. In the olden days, web pages contained little more than text. Text on paper is structured into paragraphs, which go down the page, one after the other. So web pages did the same, and this still continues as the starting point today.

In other words, the basic element is a <p>, and these are displayed down the screen, one after the other, accounting for margins and padding. Inside a paragraph, you might have links. These will appear inline - so a link is shown on the line of text where it occurs, and after the link, the text continues. This is called normal flow. (The w3c definition is useless).

This applies to paragraphs and headings and divs, and other things which are displayed as blocks, while things like links and spans default to being inline.

So the default positioning of a block is like this - normal flow. Such positioning in css is referred to as static. You can say in css:

but this just means to position paragraphs in their default manner - one after the other

There are 3 alternatives to static - relative, absolute and fixed. We'll look at each one. relative means that the browser in effect works out where the element will be in normal flow, then moves it relative to that position.

For example, this paragraph has an id which is styled to be positioned relative, with a 'left' attribute of -40px.

The HTML is :

And the css is:

So if an element is position relative, it's position is controlled by its left, top, right and bottom style attributes. These are relative to the corresponding position of the element box if it were in normal flow.

The size (width and height) of the element is not changed. So if you fix the left and right, for example, one will be ignored.

The browser will leave a space for a relative element, as if it were in normal flow

Next, for absolute positioning, left, right, top or bottom attributes fix the position according to those values - out of normal flow, unaffected by other elements.

For example, this is positioned with left 100px and top 1050px




The HTML is :

And the css is:

See that the left, top and so on are relative to the containing element, not the page. So that yellow paragraph is inside the div with the pale blue background, so its 100px in from the left of that, not the page

Finally, fixed positioning is relative to the document window, not anything in the document - so it stays fixed when the page is scrolled.

This example is positioned fixed, as explained below. Its got right 50px, top 100px, a width of 100 and an orange background

The css is:

fixed does not work in IE6 and below.

back to webbits

Syntax highlighting by Alex Gorbatchev