Absolute and Relative CSS Positioning

Absolute and relative CSS positioning help to take CSS layout beyond a mere replacement for tables, adding extra functionality and flexibility that simply isn't possible using tables.

Relative CSS positioning

Relative CSS positioning allows us to shift our elements around in relation to where they would have been placed by default. When using relative positioning we need to specify the amount we want to shift the element, using top, left, bottom, and right, followed by a distance. For example, say we wanted to shift our logo element 10 pixels to the right and 20 pixels down; we would do it like so:

#logo {
	position: relative;
	top: 20px;
	left: 10px;

The important thing to remember is that the element will be moved relative to where it would be positioned by default. If we want to position an element at an exact position on the screen we need to use absolute positioning instead.

Absolute CSS positioning

Absolute CSS positioning allows us to position an element at an exact place on the screen. In order to do this we need to specify the co-ordinates of the upper left-hand corner of our element like so:

#logo {
	position: absolute;
	top: 30px;
	left: 40px;

Using this code would position our logo so that its top left corner began 40 pixels from the left of the browser window and 30 pixels from the top.

There is also a second type of absolute CSS positioning called fixed positioning, which we can use to locate an HTML element at an exact co-ordinate in relation to the user's screen rather than the browser window. The difference here is that the element will remain in exactly the same position even if the user scrolls down the page. A great way to visualize this is to think about how television networks display their logo in the bottom corner of the screen; no matter what the camera does, the logo stays in the same place on our screen. To use fixed CSS positioning we can do the following:

#logo {
	position: fixed;
	bottom: 20px;
	right: 20px;

In this case our logo would be fixed in position 20 pixels from the bottom and 20 pixels from the right-hand side of the user's screen. It is worth noting, however, that this does not work in some browsers, notably most versions of Microsoft Internet Explorer, so use it sparingly, if at all.