Absolute positioning
Absolute positioning works pretty differently to relative positioning, but it isn’t really any more complex. When you set position: absolute; on an element, it is taken completely out of the document flow, so it effectively takes up zero space—elements below it nudge up to fill the gap. The top, bottom, left and right values you include specify the element’s distance from the four respective edges of the nearest positioned ancestor element (usually the <body> element). See Figure 21.4 for an illustration of this.
Figure 21.4: An absolutely positioned element is taken out of the document flow, and positioned a set distance away from the sides of the nearest positioned ancestor element. Now .img02 takes up no space in the document flow, therefore .img01 and .img03 now sit right next to each other on the page.
Let’s look at an example. We’ll create a two-column layout similar to the ones from the last chapter, but using absolute positioning instead of floats—check out absolute_positioning1.html on the companion website, http://interactwithwebstandards.com. This is a simple layout with a header, footer, menu and main content column. Without positioning, it looks like Figure 21.5.
Figure 21.5: The makings of a two-column layout, but we’re not there yet.
First of all, let’s try absolutely positioning the navigation menu:
#navigation_sidebar { width: 200px; background-color: #ffffff; border: 2px solid black; margin-bottom: 20px; position: absolute; }
This gives us the result shown in Figure 21.6.
Figure 21.6: Oops—we now have a navigation menu sitting on top of our content.
Setting position: absolute; on our menu has taken it out of the document flow, so the main content has jumped upwards to fill the gap. But there is no space for the menu and we haven’t told it to go anywhere else, so it just sits there on top of the content.
To deal with this, we will set some padding on the left hand side of the content, bumping it over to the right a bit to give the menu some room, and set top and left values on the menu to move it down and right a bit, nicely into position:
#navigation_sidebar { width: 200px; background-color: #ffffff; border: 2px solid black; margin-bottom: 20px; position: absolute; top: 113px; left: 38px; } #main_content { background-color: #cccccc; border: 2px solid black; padding-left: 25%; }
This works nicely—the finished layout is shown in Figure 21.7.
Figure 21.7: The menu and content now have space to breathe—much better.