I have the following code:
.container {
position: relative;
}
.topleft {
position: absolute;
top: 8px;
left: 16px;
font-size: 18px;
}
img {
width: 100%;
height: auto;
opacity: 0.3;
}
<h2>Image Text</h2>
<p>Add some text to an image in the top left corner:</p>
<div class="container">
<img src="https://www.w3schools.com/css/trolltunga.jpg" alt="Norway" width="1000" height="300">
<div class="topleft">Top Left</div>
</div>
This is copied from w3 schools. When running this code the text "Top Left" appears on the top left of IMAGE.
I need to understand why.
In this case div with the class of container is defined with the position of relative.
But Div with the class of Topleft is not inside IMG. It is inside the div with the class of container.
How come TOP LEFT text is positioned inside the image and not container Div. img is not a nearest positioned ancestor of TopLeft Div.
======================================
Thanks for comments. I think the core reason for this behavior was the following fact:
Absolute positioned elements are removed from the normal flow, and can overlap elements.