Reputation:
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.
Upvotes: 20
Views: 89898
Reputation: 894
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.
Upvotes: 6
Reputation: 1776
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>
Upvotes: 11
Reputation: 5994
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>
Upvotes: 20