Piyush Sharma
Piyush Sharma

Reputation: 113

Absolute positioned image is positioning with respect to absolute positioned parent

I am unable to understand why the child image which is absolute positioned is getting its offset with respect to its parent which is also absolute. but, by definition it should position with respect to relative closest ancestor

.supparent {
    width:100%;
    height:300px;
    position:relative;
}

.parent {
    position:absolute;
    top : 10%;
    left:10%;
}

.im {
    position:absolute;
    top:0%;
    left:0%;
}
<div class="supparent">
    <div class="parent">
        <img src="https://tpc.googlesyndication.com/simgad/2621399702091823008" class="im">
    </div>
</div>

And what is the hack to make it position with respect to supparent

Upvotes: 0

Views: 182

Answers (1)

caramba
caramba

Reputation: 22480

By definition: from MDN

The absolutely positioned element is positioned relative to nearest positioned ancestor (non-static). If a positioned ancestor doesn't exist, the initial container is used.

See this update with some bordered colors. It does not matter if the parent is set position: relative; or position: absolute;

.supparent {
    width:100%;
    height:300px;
    position:relative;
  
  border: solid 5px orange;
}

.parent {
    position:absolute;
    top : 10%;
    left:10%;
  
    border: solid 5px red;
}

.im {
    position:absolute;
    top:0%;
    left:0%;
  
    border: solid 5px green;
}
<div class="supparent">
    <div class="parent">
        <img src="https://tpc.googlesyndication.com/simgad/2621399702091823008" class="im">
    </div>
</div>

Upvotes: 2

Related Questions