如何在容器中的图像上叠加文本——并将文本保留在容器中

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>

我不太确定是否有足够的信息。我假设您的容器宽 800 像素,高 200 像素(我使用了最小高度以防您的容器增加高度)。如果你能提供更具体的信息,那就太好了(有更复杂的方法使用对象位置 属性 (等)使这个有点 "smarter".

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;
}

您需要在 .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>