There was a small example 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>
</ul>
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 {
list-style-type:none
}
ul.lst li a {
position: relative;
display:block;
padding: 7px;
border-bottom: 1px solid #f3f2e8;
width:200px;
text-decoration:none;
font: .9em Verdana;
}
ul.lst li a:hover {
background-color:#e0e0e0;
}
ul.lst li a em {
position: absolute;
right: 7px;
top: 7px;
font-style:normal;
}
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; 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.
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.
Hello, did you managed to get 'position:relative' to work on iBooks ? With the few tests i've made, the elements seems to disappear.
ReplyDeleteThanks !
Yes, I have been able to get position: relative to work in iBooks. More soon, I promise!
ReplyDeleteLiz, are you able to give an example of this?
ReplyDeleteI was absolutely positioning text over images with no problems, until I upgraded to iBooks 1.1, and suddenly it doesn't work anymore. I'm currently trying to find a work around. If you've got any hints on how to make it work, that would be great.