繁体   English   中英

如何在容器中的图像上覆盖文本-并将文本保留在容器中

[英]How to overlay text on an image in a container--and keep the text in the container

我正在跟踪在数十亿个位置提供的解决方案,该解决方案是如何使用relativeabsolute定位在图像上叠加文本。 问题在于, position: absolute的文本会从其容器中弹出,并移至最大的topright等。

我很乐意使用背景图像,但是随后我需要技巧来使容器与图像的大小匹配,而且我不知道使它流畅的方法。

似乎是一个非常简单的问题,人们一直在寻找解决方案。 还有在不透明图像上覆盖文本的事情,需要使用: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> 

您需要在.container上设置position:relative ,这是.text的正确容器。 请注意, img.text的同级.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> 

我不太确定是否有足够的信息。 我假设您的容器的宽度为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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM