【问题标题】:How to overlay text on an image in a container--and keep the text in the container如何在容器中的图像上覆盖文本 - 并将文本保留在容器中
【发布时间】:2018-03-08 07:20:38
【问题描述】:
我正在关注如何使用relative 和absolutepositioning 在图像上覆盖文本的解决方案。问题是带有position: absolute的文本从它的容器中弹出并到了最大top、right等。
我很乐意使用背景图片,但是我需要一些技巧来让容器与图片的大小相匹配,而且我不知道如何让它变得流畅。
似乎是一个非常简单的问题,人们一直在寻找解决方案。还有在不透明图像上覆盖文本的事情,需要使用:after。希望对这些情况有直接的选择。
.container {
margin: 0 10%;
}
.container img {
position: relative;
width: 100%;
}
#div1 .text {
position: absolute;
bottom: 0;
right: 0;
}
#div2 .text {
position: absolute;
top: 0;
left: 0;
}
<div id="div1" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Top Image</h3>
<p>This text should be in the bottom right of the top image.</p>
</div>
</div>
<div><p>A bunch of miscellaneous text here.</p></div>
<div id="div2" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Lower Image</h3>
<p>This should be in the top left of the lower image.</p>
</div>
</div>
【问题讨论】:
标签:
html
css
image
background-image
overlay
【解决方案1】:
您需要在.container 上设置position:relative,这是.text 的正确容器。请注意,img 是 .text 的兄弟,而不是其容器。
.container {
margin: 0 10%;
position: relative;
}
.container img {
width: 100%;
}
#div1 .text {
position: absolute;
bottom: 0;
right: 0;
}
#div2 .text {
position: absolute;
top: 0;
left: 0;
}
<div id="div1" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Top Image</h3>
<p>This text should be in the bottom right of the top image.</p>
</div>
</div>
<div><p>A bunch of miscellaneous text here.</p></div>
<div id="div2" class="container">
<img src="http://placehold.it/800x200" />
<div class="text">
<h3>Lower Image</h3>
<p>This should be in the top left of the lower image.</p>
</div>
</div>
【解决方案2】:
我不太确定是否有足够的信息。我假设您的容器是 800 像素宽和 200 像素高(我使用了最小高度以防您的容器增加其高度)。如果您可以提供更具体的信息,那就太好了(使用对象位置属性(等)有更复杂的方法可以使这更“智能”。
img {
max-width: 100%;
display: block;
height: auto;
}
.container {
position: relative;
min-height: 200px;
width: 800px;
margin: 0 10%;
}
.container img {
z-index: 500;
top: 0;
left: 0;
}
.container .text {
position: absolute;
z-index: 1000;
}
#div1 .text {
bottom: 0;
right: 0;
}
#div2 .text {
position: absolute;
top: 0;
left: 0;
}