Difference between Absolute and Relative CSS Positioning


CSS Positioning

This tutorial is for css beginners who has just come across the CSS Positioning attributes called absolute and relative but can' t find themselves comfortable with their real meaning and their implementation.







CSS Positioning

   Tutorial Details
   Tool : CSS
   Difficulty level : Intermediate

This tutorial is for css beginners who has just come across the CSS Positioning attributes called absolute and relative but can' t find themselves comfortable with their real meaning and their implementation.
1. Absolute Positioning

    First consider a case of an image which is just placed inside the body tag with an 
    absolute positioning.
    
    Now the image will be positioned 20px from top and 20px from left with respect to the  
    parent  element. In this case there is no parent element and hence the image will be 
    placed according to the browser window.
    
    Absolute positioning will make that particular element (in this case image) to act as 
    an independent element breaking it out of the natural flow of the other elements.   
    Now this element can also be superimposed on the other elements i.e it will act as a 
    separate layer.

<html>
<head>
<style>
img{
position:absolute;
left:10px;
top:10px;
}
</style>
</head>
<body>
<img src="thewwwdesigners.png">
</body>
</html>
2. Relative Positioning

       Now we will place the image inside a div tag, hence the div tag will act as a parent
       element  for the image tag. To understand the working, we will position the div tag
       as relative and make the image tag as absolute. 
       
       Hence the <div> tag act as a parent tag for the image tag. Similarly everthing
       this div tag will be positioned absolutely accordingly.
  
<html>
<head>
<style>
div{
position:relative;
top:100px;
left:100px;
width:500px;
height:100px;
background-color:red;
}
img{
position:absolute;
left:20px;
top:20px;
width:200px;
height:80px;
}
</style>
</head>
<body>
<div>
<img src="thewwwdesigners.png">
</div>
</body>
</html>