Overlay Div on image

user3238291 picture user3238291 · Jan 28, 2014 · Viewed 64.4k times · Source

So I have a <div> with relative positioning, and it has a child <img> with absolute positioning.

<div style="position: relative;">
  <img src="image.png" style="position: absolute;" />
  <span id="overlay_text">OVERLAY</span>
</div>

The problem is that it needs to be at the top (higher on the Y axis, or closer to the top of the screen), but it is only measured in distance from the bottom.

Answer

Joe Conlin picture Joe Conlin · Jan 28, 2014

Use z-index and top. This will layer the div on bottom, the image and then the span (overlay) on top. To set the positioning from the top edge, use top, which can be used with negative numbers if you need it to be higher on the Y axis than it's parent. The example below will move the span 10px above the top of it's parent div.

<div style="position: relative; z-index: 1;">
  <img src="image.png" style="position: absolute; z-index: 2;" />
  <span id="overlay_text" style="position: relative; top: -10px; z-index: 3;">OVERLAY</span>
</div>