I have several divs within a larger divs. Is it possible to position all these divs relative to the top left corner of the parent div? This will make positioning easier for certain tasks as all the inner divs’ coordinates will be relative to the same reference point. At the moment using position: relative just offsets its position from where it would be at without being affected by position: relative.
I have several divs within a larger divs. Is it possible to position all
Share
Set the parent/containing div to
position:relative. Then, set the child divs topostion:absolute. The children will then be positioned absolutely, but relative to the containing div, not relative to the overall page.Here’s an example: http://jsfiddle.net/jfriend00/GgNsH/.
HTML:
CSS:
Each child will be positioned at it’s top/left value from the top/left corner of the container.
It works because that’s how
position: absoluteworks. It positions the element relative to the first positioned parent (a parent that has a position value ofrelative,absoluteorfixed) or if no parents are positioned, then it uses the top/left corner of the document as the reference. This is not a trick, but how it’s documented to work and it’s extremely useful.