为什么文本显示在使用 CSS 的绝对定位图像后面?

Cla*_*aud 4 css position image z-order absolute

使用此 HTML,我无法弄清楚为什么文本显示在图像后面:

<div style="position: relative">
<img src="image_url_here" style="position:absolute; top: 10px; left: 10px;" />  
This is some text, drawn on the page after the image, why is it drawn behind the image?
</div>
Run Code Online (Sandbox Code Playgroud)

?

在 Mac 和 PC 上的 Chrome 和 PC 上的 IE 中测试。

Jim*_*mmy 6

这篇文章可以回答你的问题:z-index解释

TL;DR:定位元素堆叠在非定位元素上,因此只需添加 position: relative到您想要堆叠在顶部的文本。

<div style="position: relative">
    <img src="https://via.placeholder.com/150" style="position:absolute; left: 10px;" />  
    <span style="position:relative">This is some text</span>
</div>
Run Code Online (Sandbox Code Playgroud)


Tom*_*zan 2

这是因为您将图像的位置设置为绝对位置。

  • 虽然这也让我微笑,但不幸的是它根本没有帮助。 (4认同)