Rana Adnan
3 months ago
Ranacountry asked

For position: absolute, does the parent element have to contain the child element?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hi Rana Adnan,

Yes, the element you want to position absolutely must be inside the parent in the HTML.

But one more important thing: it will be positioned relative to the nearest parent that has a position set like relative, absolute, or fixed. Most of the time we set the parent to position: relative; so the child stays inside that box.

Example:

.parent { position: relative; }
.child  { position: absolute; top: 0; right: 0; }

If no parent has a position set, the absolute element is positioned relative to the page (the viewport/document), which is why it can jump to a weird place.

If you have more questions, I am here to help 😊

CSS
This question was asked as part of the Learn CSS course.