Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS: Positioning a child element relative to its parent using any position property on the parent

<div style="width: 300px; height: 300px;">
   <p>Position me relative to my parent.</p>
</div>

In the above HTML, let’s say I want that p element to go to the bottom of the parent div. It’s common to use the following CSS:

div {
   position: relative;
}

p {
   position: absolute;
   bottom: 0;
}

My question is: Could I also achieve this by using any position declaration(other than static) for the parent?

I’ve been trying to find concrete proof of this but the CSS spec is inaccessible(won’t load) and various reference sites like MDN and w3schools say "An element with position: absolute; is positioned relative to the nearest positioned ancestor," which is a little vague.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://www.w3schools.com/css/css_positioning.asp

https://developer.mozilla.org/en-US/docs/Web/CSS/position

In my tests, it seems that any ancestor that has a position other than the default of static can work for setting the child relative to.

https://jsfiddle.net/saywxme4/16/

Hoping to hear from someone who knows for sure on this. References from authoritative sources are greatly appreciated.

>Solution :

The question is:

Could I also achieve this [positioning the p element at the bottom] by using any position declaration(other than
static) for the parent?

Yes

From MDN:

A positioned element is an element whose computed position value is
either relative, absolute, fixed, or sticky. (In other words, it’s
anything except static.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading