decoration
Aug
31
2008

CSS - absolute positioning

For a long time I avoided using positioning in CSS. I think the main reason was that I didn´t really understand it. Absolute positioning was the worst. In stead I used floating alot and it worked most of the time even though it sometimes gave me a lot of headaches.
But as times went by I started to use positioning more and more and I discovered that it is the perfect tool to “positioning” elements on a web-page.
There is one very important rule that one has to remember when using absolute positioning. The parent element has to be positioned relative or absolute. Let me explain with the words of Andy Clarke.

An absolutely positioned element is positioned first to its closest POSITIONED ancestor. If there is no positioned anchestor, the element is positioned to the root element <html>.
Andy Clarke - transcending CSS

To give you an example of how to use absolute positioning i want to show you how i positioned the elements in the footer of this pages.
The xhtml code looks like this

<div id="footer">
    <ul id="icons">
     <li><a href="#"><img src="images/facebook-icon.png" alt="bippi on facebook" /></a></li>
     <li><a href="#"><img src="images/flickr-icon.png" alt="bippi on flickr" /></a></li>
     <li><a href="#"><img src="images/rss-icon.png" alt="rss feed" /></a></li>
    </ul>
    <span id="icon-text"></span> 
    <span id="copyright">Copyright © 2008 bippi</span>
   </div>

There is nothing complicated here. We have one <div> and inside that <div> there is a one un-orded list and two spans.

The CSS code looks like this

#footer
{ 
 position:relative;
 width:951px;
 height:48px;
}
#footer ul li
{
 display:inline;
}
#icons
{
 position:absolute;
 left:20px;
 top:10px;
}

#icon-text
{
 position:absolute;
 left:172px;
 top:20px; 
}
#copyright
{
 position:absolute;
 top:20px;
 right:20px; 
}

The main thing here is that the footer div is given a relative position and then we are able to use “top”, “right” and “left” to correctly position the three elements.

Leave a message