CSS: contextual positioning

In CSS, contextual positioning is the way by which two positioned elements relate to each other. When you use absolute positioning in CSS, a positioned element will always be positioned with respect to the global viewport of the document. But when a positioned element (relatively or absolutely) contains one or more child elements which are also positioned, then these elements will be positioned using their parent element (or a positioned ancestor) as a reference, not the viewport. In other words, the coordinates of the child elements will be calculated with respect to their parent element (or ancestor). Suppose that you have the following CSS rules:

#parent {
    position: absolute;
    width: 400px;
    height: 200px;
    top: 0;
    left: 0;
}

#parent #child {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 0;
    right: 0;
}

The result is depicted below.

As you can see, contextual positioning is a powerful way of handling positioned elements and it turns out to be very useful, especially when you have to deal with complex layouts and you don't want to use floats.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.