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
.
By default, if no parent element with a non-static position is found the div with position absolute is rendered relative to the document itself. We can make the dialog div positioned relative to the parent div by first making it a child of the parent div and then setting the parent position to relative.
Yes. You will not be able to work with absolutely positioned elements any more, for example - the absolute positioning will always be relative to the parent element, which is almost never the desired result.
Relative Positioning You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document. Move Left - Use a negative value for left. Move Right - Use a positive value for left. Move Up - Use a negative value for top.
Set the parent/containing div to position:relative
. Then, set the child divs to postion: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:
<div id"otherStuff" style="height: 100px; background-color: #777;"></div>
<div id="container">
<div id="child1" class="child"></div>
<div id="child2" class="child"></div>
<div id="child3" class="child"></div>
</div>
CSS:
#container {position: relative;}
.child {position: absolute; height: 10px; width: 10px; background-color: #777;}
#child1 {top: 10px; left: 10px}
#child2 {top: 30px; left: 30px}
#child3 {top: 50px; left: 50px}
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: absolute
works. It positions the element relative to the first positioned parent (a parent that has a position value of relative
, absolute
or fixed
) 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With