Html 在图像上叠加 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21395662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overlay Div on image
提问by Joe Conlin
So I have a <div>
with relative positioning, and it has a child <img>
with absolute positioning.
所以我有一个<div>
相对定位,它有一个<img>
绝对定位的孩子。
<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.
问题是它需要在顶部(在 Y 轴上更高,或者更接近屏幕顶部),但它仅以距底部的距离为单位进行测量。
回答by Joe Conlin
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.
使用z-index
和top
。这会将 div 分层在底部,图像,然后跨度(覆盖)在顶部。要从顶部边缘设置定位,请使用top
,如果您需要它在 Y 轴上高于它的父轴,它可以与负数一起使用。下面的示例将跨度移动到其父 div 顶部上方 10px。
<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>
回答by kenny
This is in some cases a better solution, so the parent div gets height of the image:
在某些情况下,这是一个更好的解决方案,因此父 div 获取图像的高度:
<div style="position: relative; z-index: 1;">
<img src="image.png" />
<span style="position: absolute; top: 0px; z-index: 3;">OVERLAY</span>
</div>
回答by Kevin Farrugia
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.
取决于您正在寻找的确切内容,但基于@Joe Conlin 的答案的一个简单示例是添加负的最高值。
Also a slight correction on @Joe Conlin, the span should have position absolute not relative I think.
还有对@Joe Conlin 的轻微修正,我认为跨度应该具有绝对位置而不是相对位置。
http://jsfiddle.net/KevinFarrugia/fj83ytwp/1/
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:
CSS:
.parent{
position: relative;
margin: 2em;
}
.parent img{
position: absolute;
}
.parent .overlay{
position: absolute;
top: -1em;
text-align: center;
width: 100%;
}