I have two divs inside another div, and I want to position one child div to the top right of the parent div, and the other child div to the bottom of the parent div using css. Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. How can I do this?
Sample html:
<div id="father">
<div id="son1"></div>
<div id="son2"></div>
</div>
If you don't give any position to parent then by default it takes
static
. If you want to understand that difference refer to this exampleExample 1::
http://jsfiddle.net/Cr9KB/1/
Here parent class has no position so element is placed according to body.
Example 2::
http://jsfiddle.net/Cr9KB/2/
In this example parent has relative position hence element are positioned absolute inside relative parent.
Incase someone wants to postion a child div directly under a parent
Working demo Codepen
This works because
position: absolute
means something like "usetop
,right
,bottom
,left
to position yourself in relation to the nearest ancestor who hasposition: absolute
orposition: relative
."So we make
#father
haveposition: relative
, and the children haveposition: absolute
, then usetop
andbottom
to position the children.