使文本出现在相对定位的图像前面
Make text appear in front of an relatively positioned image
我有一张 position: relative
的图片,它覆盖了一些文字。
有没有办法让文字出现在图片前面?
我试过 z-index
但无济于事。
这是我的代码
h2 {
padding-top: 100px;
}
img {
position: relative;
top: -150px;
}
<h2>1715</h2>
<div class="img-wrapper">
<img src="http://cdn.xl.thumbs.canstockphoto.com/canstock24510515.jpg" >
</div>
h2 {
padding-top: 100px;
z-index:1;
position:relative;
}
img {
position: relative;
top: -200px;
z-index:0;
}
<h2>1715</h2>
<div class="img-wrapper">
<img src="https://bootstrapbay.com/blog/wp-content/uploads/2014/05/unslpash-desert-road_uvsq5s.png" >
</div>
如果您不想更改 html 结构,可能的解决方案。
为了使 z-index 正常工作,不能将其定位为静态(默认)。在这种情况下,尝试 position: relative 和 z-index 将起作用。
尝试将两个元素放入容器中 position: relative
。
然后你可以完全定位 children 并应用 z-index
到它们。
我还将插图的文本居中。
始终牢记:除非您使用的是弹性项目或网格项目,否则必须对元素进行定位才能使 z-index
正常工作 ()。
#container {
position: relative;
display: inline-block;
}
h2 {
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
margin: 0;
}
img {}
<div id="container">
<h2>1715</h2>
<div class="img-wrapper">
<img src="http://cdn.xl.thumbs.canstockphoto.com/canstock24510515.jpg">
</div>
</div>
你可以这样解决。
h2 {
padding-top: 94px;
position: relative;
z-index: 999;
}
img {
position: absolute;
top: 0;
}
h2 {
padding-top: 94px;
position: relative;
z-index: 999;
}
img {
position: absolute;
top: 0;
}
<h2>1715</h2>
<div class="img-wrapper">
<img src="http://cdn.xl.thumbs.canstockphoto.com/canstock24510515.jpg" >
</div>
我有一张 position: relative
的图片,它覆盖了一些文字。
有没有办法让文字出现在图片前面?
我试过 z-index
但无济于事。
这是我的代码
h2 {
padding-top: 100px;
}
img {
position: relative;
top: -150px;
}
<h2>1715</h2>
<div class="img-wrapper">
<img src="http://cdn.xl.thumbs.canstockphoto.com/canstock24510515.jpg" >
</div>
h2 {
padding-top: 100px;
z-index:1;
position:relative;
}
img {
position: relative;
top: -200px;
z-index:0;
}
<h2>1715</h2>
<div class="img-wrapper">
<img src="https://bootstrapbay.com/blog/wp-content/uploads/2014/05/unslpash-desert-road_uvsq5s.png" >
</div>
如果您不想更改 html 结构,可能的解决方案。
为了使 z-index 正常工作,不能将其定位为静态(默认)。在这种情况下,尝试 position: relative 和 z-index 将起作用。
尝试将两个元素放入容器中 position: relative
。
然后你可以完全定位 children 并应用 z-index
到它们。
我还将插图的文本居中。
始终牢记:除非您使用的是弹性项目或网格项目,否则必须对元素进行定位才能使 z-index
正常工作 (
#container {
position: relative;
display: inline-block;
}
h2 {
position: absolute;
z-index: 1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
margin: 0;
}
img {}
<div id="container">
<h2>1715</h2>
<div class="img-wrapper">
<img src="http://cdn.xl.thumbs.canstockphoto.com/canstock24510515.jpg">
</div>
</div>
你可以这样解决。
h2 {
padding-top: 94px;
position: relative;
z-index: 999;
}
img {
position: absolute;
top: 0;
}
h2 {
padding-top: 94px;
position: relative;
z-index: 999;
}
img {
position: absolute;
top: 0;
}
<h2>1715</h2>
<div class="img-wrapper">
<img src="http://cdn.xl.thumbs.canstockphoto.com/canstock24510515.jpg" >
</div>