In my HTML code, I have a parent div that contains an image, and a child div that holds another image. I wanted the child image to appear in the top-left corner of the parent image by setting the position of the child image to absolute
, and the parent's position to either relative
or absolute
.
According to W3Schools, for the absolute
property to work correctly, the element should be positioned relative to its first non-static ancestor element. So, I assumed that I needed to set a non-static position for the parent.
However, I was surprised to see that even without setting the position of the parent (defaulting to "static"), the child image still appeared nicely in the top-left corner.
I am now wondering why I did not have to set the position of the parent to a non-static value for the absolute
property to function properly. Did I misunderstand how absolute
positioning works?
<div class="parent">
<img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300">
<div class="child">
<img src="http://xiostorage.com/wp-content/uploads/2015/10/test.png" width="200">
</div>
</div>
/*.parent {
position:relative;
}*/
.child {
display:none;
position:absolute;
left:0;
}
.parent:hover .child {
display:initial;
}
View the JSFiddle example here.
Update: Connexo provided an updated code snippet.
Try uncommenting the position
for the parent to uncover the mystery. For more information, refer to the accepted answer below.
<h1>
Positioning test
</h1>
<div class="parent">
<img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300">
<div class="child">
<img src="http://xiostorage.com/wp-content/uploads/2015/10/test.png" width="200">
</div>
/*
.parent {
position:relative;
}*/
.child {
display: none;
position: absolute;
left: 0;
top: 0;
}
.parent:hover .child {
display:initial;
}