Relative positioning in CSS

Below are the same two DIVs one after the other as on the last page. The first one is still position:static. its position defaults to just after this paragraph

The second DIV is positioned relative to its static position (as on the last page).

The above is achieved using this CSS in the HEAD in a STYLE element or in an external stylesheet:

            
#second {
    position:relative;                
    top:10px;
    left:100px;                
    height:80px;
    width:400px;
    background-color:blue;
    padding:0px;
    margin:0px;
    border:0px;            
}
        

The important changes are the first three lines. They make the DIV move down 10px and across 100px from where it would have been otherwise.

This seems easy so far but change the first element to a relative position as well and it all starts to get complicated:

#first {
    position:relative;
    top:50px;
    left:50px;                
    height:100px;
    width:300px;
    background-color:green;
    padding:0px;
    margin:0px;
    border:0px;
}            
        

You might think the second one would still be 10px below the first one because as the first one moves down the second would be forced down as well. It isn't. Try it and you get:

You can see that the first one has moved down 50px as there is a gap after the paragraph above it.

The DIVs overlap. This is because the second DIV's position is based on the static position of the first DIV and not where it appears to be! Try to think of it as everything having an actual position on the page but when you use relative positioning the element appears somewhere else! All the other elements on the page think it is where it actually is but the user sees it where it is by relative positioning:

You created a Web page for the static positioning page called positioning.html. Change the positioning for the DIVs from static to relative as shown above. Then play with TOP and lEFT values. You can use negative values. Also try using RIGHT and BOTTOM instead. Finally try using % and em instead of px. Practice is essential.

Once you have the hang of relative positioning change it back to static. Leave the top/left or other styles but notice that when you test the page they are ignored because static positioning does not allow for anything other than the default position of an element.

submit to reddit Delicious Tweet