Monday, November 30, 2009

Why is position:relative necessary when you're positioning absolutely?

So I'm reading Dan Cederholm's new book, Handcrafted CSS: More Bulletproof Web Design. I'm really liking it.

There is a small example in the intro that deals with absolute positioning that I want to highlight. He's talking about formatting a list of coffee drinks that have a title and a price. The goal is to have the link be the entire line so that it makes it easy for readers to click on their desired cup of coffee.

The original code looks like this:

<ul class="lst">   
<li><a href="#"><em>2.79</em> Latte</a></li>
<li><a href="#"><em>2.99</em> Cappuccino</a></li>
<li><a href="#"><em>1.80</em> Cafe Americano</a></li>
<li><a href="#"><em>2.00</em> Espresso</a></li>
<li><a href="#"><em>10.49</em> Caramel Macchiato</a></li>

Cederholm suggests using absolute positioning, with code much like the following (his is part of a larger web page and so I've adjusted it to appear on its own):

ul.lst li {

ul.lst li a   {
     position: relative;
     padding: 7px;
     border-bottom: 1px solid #f3f2e8;
     font: .9em Verdana;
ul.lst li a:hover {
ul.lst li a em  {
     position: absolute;
     right: 7px;
     top: 7px;

The result can be seen here.

And though Cederholm says the position:relative line is necessary, he doesn't explain why. The reason is that when you position an element absolutely—in this case the coffee prices, which are em elements—their position is calculated with respect to the nearest positioned ancestor, or if there is none, to the body element. Since he wants the prices to go in the same line as the a element that contains them, he must position the a element. By adding position:relative to the definition for the a element, it becomes positioned, and any descendants that are absolutely positioned will be positioned relative to it. This happens even though he's not defining any offsets; that is, the a elements stay in their natural place in the flow.

You can find more information about relative and absolute positioning on pages 178-179 in my HTML, XHTML, and CSS, Sixth Edition: Visual QuickStart Guide.

Also note that Cederholm concludes this example by showing how absolute positioning is not very flexible for text elements. That is, when the text is enlarged, the name of the coffee and its price overlap each other. Instead, absolute positioning makes more sense if one of the pieces is a static image whose size can always be accounted for.


Anonymous said...


i am live in tehran(iran)

i am studing your book (xhtml and css). your book is very well.

very very thank you

sayyed abolfazl hashemi 22years.tehran

Liz Castro said...

Thanks! So glad you've found it useful.

My Books