当前位置: 动力学知识库 > 问答 > 编程问答 >

html - Overlay Div on image

问题描述:

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.

网友答案:

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>
网友答案:

Depends on what you are looking for exactly, but a simple example based on @Joe Conlin's answer would be to add a negative top value.

Also a slight correction on @Joe Conlin, the span should have position absolute not relative I think.

http://jsfiddle.net/KevinFarrugia/fj83ytwp/1/

<div class="parent">
  <img src="http://www.gstatic.com/webp/gallery/1.webp" />
  <span class="overlay">OVERLAY</span>
</div>

CSS:

.parent{
    position: relative;
    margin: 2em;
} 

.parent img{
    position: absolute;
}

.parent .overlay{
    position: absolute;
    top: -1em;
    text-align: center;    
    width: 100%;
}
网友答案:

This is 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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: