Why is text displayed behind absolute positioned image with CSS?

11.2k Views Asked by At

Using this HTML, I can't figure why the text displays behind the image:

<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>

?

Tested in Chrome on Mac & PC and IE on PC.

4

There are 4 best solutions below

2
On

It's because you set the image's position to absolute.

0
On

Refer this https://developer.mozilla.org/en-US/docs/Web/CSS/position

Try this or set as per your requirement

<div style="position: relative">
<img src="image_url_here" style="position:relative; top: 10px; left: 10px;" />  
This is some text, drawn on the page after the image, why is it drawn behind the image?
</div>
0
On

This article can answer your question: z-index explained

TL;DR: Positioned elements are stacked over non-positioned elements, so just add position: relative to the text you want stacked on top.

<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>

0
On

Might be a bit toooo late to answer, but could be useful for somebody: The solution is to set z-index: -1; to the image. Probably should wrap text in <p>.