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开发者_如何学Go moment using position: relative
just offsets its position from where it would be at without being affected by position: relative
.
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.
精彩评论