Unable to understand the position

Hi, I’m trying to position the element absolutely relative to the other element but I’m unable to do it. I’m not getting the error. Please help.

The following is my code. Iam trying to postion the div.absolute element on the div.container element

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <div class="container">
        <div class="item">hey</div>
        <div class="item">today</div>
        <div class="item">bottom</div>

    <div class="absolute">





Absolute positioning is in relation to the closest positioned ancestor (parent, grandparent, etc…). So div.absolute will be positioned relative to the body, not div.container. I’m not sure what you are trying to do here but you might want to consider flexbox or grid instead if you are trying to position siblings relative to each other.

I’m trying to position the div.absolute element on the div.container element so I’ve added postion :relative to the div.container

I’m not sure I understand what you mean by this. Do you mean you want div.absolute to be physically on top of div.container?

Yes. But I didn’t understand the concept of position relative and absolute. Why the div.absolute is completely relative to the body instead of div.relative (even after I’ve added the position:relative property to the div.relative)

MDN position

Because that’s the way absolute positioning works. From the MDN article:

“The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block.”

div.container (the one with relative positioning) is not an ancestor of div.absolute, it is a sibling. The nearest ancestor is the body.

Adding position relative to div.container does not affect affect div.absolute.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.