20

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.

  • 2
    Can you make a [JSFiddle](http://jsfiddle.net) ? – Raptor Jan 28 '14 at 02:24
  • So you need the `` to be on top of the ``? – Blundering Philosopher Jan 28 '14 at 02:24
  • 1
    Take a look at [this answer](http://stackoverflow.com/questions/21371594/display-div-or-span-over-image-on-hover/21371665#21371665) it should do what you want. – Josh Crozier Jan 28 '14 at 02:24
  • by default, the `` has `left: 0; top: 0` if no other CSS inherited. This acts as the same as no `position: absolute`. What exactly do you want? Does `z-index` or set the image to background image help ? – Raptor Jan 28 '14 at 02:26

3 Answers3

19

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>
Joe Conlin
  • 5,976
  • 5
  • 25
  • 35
  • Sorry, I mean top on the Y axis, as in higher on the screen, not on top of the image. I will clarify above. –  Jan 28 '14 at 02:29
9

This is in some cases a better solution, so the parent div gets height of the image:

<div style="position: relative; z-index: 1;">
  <img src="image.png" />
  <span style="position: absolute; top: 0px; z-index: 3;">OVERLAY</span>
</div>
kenny
  • 1,628
  • 20
  • 14
6

I'm aware this is an old question but I've noticed several examples using z-index, which may not be necessary for this use case and can become problematic with dozens of stacked elements.

N.B.: Elements are stacked from bottom to top. In this case:

<span>OVERLAY</span> is declared below <img />. Therefore, span is stacked above img.

<div style="position: relative;">
  <img src="https://upload.wikimedia.org/wikipedia/commons/6/67/Delta-shield.png" style="position: absolute;" />
  <span id="overlay_text" style="position: relative; top: 8rem; margin-left: 80px">OVERLAY</span>
</div>

More information on stacking can be found here.

Remy
  • 822
  • 12
  • 18