Why is text displayed behind absolute positioned image with CSS?

Claud picture Claud · Sep 2, 2013 · Viewed 7k times · Source

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.

Answer

Jimmy picture Jimmy · Nov 26, 2018

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>