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>
Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.
fixed : the element is removed from the flow of the document like absolutely positioned elements. In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.
If you position it as absolute , then you're positioning it relative to its closest ancestor which is fixed or relative ... Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.
The one key thing to remember when trying to position a child div relative to it's parent is that the child should be given the CSS property position:absolute; and the parent set to either position:absolute; or position:relative;.
#father { position: relative; } #son1 { position: absolute; top: 0; } #son2 { position: absolute; bottom: 0; }
This works because position: absolute
means something like "use top
, right
, bottom
, left
to position yourself in relation to the nearest ancestor who has position: absolute
or position: relative
."
So we make #father
have position: relative
, and the children have position: absolute
, then use top
and bottom
to position the children.
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