Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position absolute but relative to parent

Tags:

html

css

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> 
like image 487
BlaShadow Avatar asked May 07 '12 18:05

BlaShadow


People also ask

How do you absolute position relative to parents?

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.

Can position fixed be relative to parent?

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.

Can an element have position absolute and relative?

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.

How can you set position of a child element with reference to its parent element?

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;.


1 Answers

#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.

like image 186
Domenic Avatar answered Sep 26 '22 09:09

Domenic