I need to position divs within divs, and I am getting crazy. I’ve read many docs on the net, but I am still not clear about behavior of relative and absolute positioning when divs are embedded.
Someone came up with the following:
The best way I’ve found to understand absolute positioning is that
position:relative looks “downstream” to child elements and
position:absolute looks “upstream” to parent elements. That is, when
you tell an HTML element to be absolutely positioned, it’s going to
look “up” to its parent elements until it finds one that is set to
position:relative, and will position itself based on that. If it
doesn’t find one, it will position itself with respect to the
by default.
Is this correct for all browsers? Is this a complete explanation?
My issue is that I have several divs embedded in several divs. I need to position some child div within a parent div, with high precision (for example top 33, left 9). The parent div can be embedded in a grand-parent div, with high precision too, etc…
How does one solve this issue for all browsers? Should I create a super relative parent div from which the whole hierarchy of div should be positioned as absolute?
EDIT
From current answers, I have an extra question: does one have to explicitly declare a relative or absolute position in each div to make positioning work? In other words, if a div does not have a relative or absolute position, it is not taken into account when computing positions?
FOR THE RECORDS
The answer to the above question is yes.
I find it a little easier to understand this way:
If an item is
position: relative, then any style settings for top, bottom, left, right positions are relative to where the item would have been in the normal layout flow. So:pushes an item 10px down lower than it would have otherwise been in the normal HTML layout.
If an item is
position:absolute, then it is positioned relative to whatever the closest parent that isposition: relativeorposition: absoluteor relative to the body element if no parents meet that criteria. For example, if the immediate parent is `position: relative’ and the child is:Then, the object will be positioned down and to the right by 10px from the upper left corner of the parent. When an object is
position: absolute, it is removed from the layout of the page and it does not affect the layout of any other objects (except it’s own children).As an example, if you want to position three images on top of one another in a container object (perhaps so you can cycle through them in a slideshow, you would do so with this CSS: