Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Positioning relative to corner of Div

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.

like image 662
Nyxynyxx Avatar asked Jul 04 '11 23:07

Nyxynyxx


People also ask

How do you position something relative to another div?

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.

Is it bad to use position relative in CSS?

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.

How do I move a relative position in CSS?

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.


1 Answers

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.

like image 76
jfriend00 Avatar answered Sep 27 '22 20:09

jfriend00