HTML and CSS

Absolute Positioning: To the Root Element

Okay, enough terminology. It's time to have some fun and actually put positioning to work! Absolute positioning positions an element box in relation to its containing block. When you position something absolutely, you take it completely out of the normal flow. In easy terms, this means that any box you position will always be positioned to either its explicit container or to the html root element (not the viewport), no matter what other content might be on the page.

Oh, good! Now you get to see why I had to spend time up front to detail the terminology. In Example 12-3, I've placed a header and a paragraph into a containing block, and then positioned the block to an offset of 100 pixels from the left and 50 pixels from the top.

Example 12-3. Absolutely positioning a block to the root element
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
           "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>working with style</title>
<style type="text/css">
#content {
           position: absolute;
           left: 100px;
           top: 50px;
           border: 1px solid red;
           }
</style>
</head>
<body>
<div id="content">
<h1>The Black Cat</h1>
<p>I married early, and was <a href="http://www.poemuseum.org/">happy to find</a> in my
 wife a disposition not uncongenial with my own. Observing my partiality for domestic pets,
 she lost no opportunity of procuring those of the most agreeable kind. We had birds, gold
 fish, a fine dog, rabbits, a small monkey, and a cat.</p>
</div>
</body>
</html>

Because there's no other containing block explicitly defined, the block will be positioned to the root element of html. I placed a screen shot that excluded any browser chrome in Photoshop so you can see how the box is now positioned absolutely to its containing block (see Figure 12-5). Figure 12-6 shows the same box in relation to other page elements.

Figure 12-5. Absolutely positioning the content div.

Figure 12-6. The absolutely positioned box with an explicit widthcontent flows within the box, which remains positioned despite other document elements, making it crystal clear what is meant by an absolute box being completely removed from the normal flow.