Search code examples
csscss-positionabsolute

CSS Positioning: Setting the child to absolute position and parent to static position


If i set the position of a child div to absolute then to position it with respect to the parent, I have to set the position of the parent to relative, right? Does it also work if I set the position of the parent to anything else other than relative like static, absolute, fixed, or sticky?

When I set the position of the child div to absolute and the position of the parent div to relative then the child gets positioned with respect to the parent but it does not work when I set the position of the parent to static, why is that? Absolute positioned child/descendant gets positioned relative to the nearest positioned parent/ancestor but when the positioned ancestor is static, it does not work and gets positioned with respect to the top left corner of the webpage rather than the parent.


Solution

  • Yes, you are right. The parent's position can be anything other than static, because static is the default positioning for an element if you don't specify any.

    This way, we can tell the browser, with respect to which parent, we want to absolutely position a child element (by setting explicitly, a non static position on the desired parent)