CSS绝对定位为何与图片重叠?容器相对定位原理疑问
Great question—let's unpack this behavior clearly and step by step.
First, let's recap the key code snippets we're working with:
CSS
.container { position: relative; } .topleft { position: absolute; top: 8px; left: 16px; font-size: 18px; } img { width: 100%; height: auto; opacity: 0.3; }
HTML
<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>
Now let's break down the core reasons behind this behavior:
Your core insight is exactly right: Absolute-positioned elements are removed from the normal document flow. This means they don't take up space like regular block or inline elements, and can freely overlap with other content on the page. That's why the
.topleftdiv sits directly on top of the image instead of pushing it out of the way.The positioning reference is the
.container, not the image:
You're correct that.topleftisn't nested inside the<img>tag, and the image itself isn't a positioned ancestor (it has the defaultposition: static). But the parent container.containerhasposition: relativeset—and for any absolute-positioned element, its positioning is calculated relative to the closest ancestor with a non-static position (relative, absolute, fixed, or sticky).Since
.containeris that ancestor,.topleftuses.container's top-left corner as its origin point. And because the image is set towidth: 100%, it fills the entire width of.container—so.container's top-left corner lines up perfectly with the image's top-left corner. That's why the text looks like it's anchored directly to the image, even though it's positioned relative to the parent container.
In short: The absolute-positioned text anchors to its positioned parent box, which happens to wrap the full-width image. The text overlaps the image because absolute positioning removes it from the normal content flow.
内容的提问来源于stack exchange,提问作者S Nash

