如何在网格中的图像上放置文本

How to position text over an image in a grid

我正在努力创建一个简单的图像网格,上面覆盖文本。图像是文档的语义部分,因此不能是背景图像。

现在网上查了下好像是这样的:

HTML

<article>
   <img class="image" src="image.png"/>
   <p class="text">Text to overlay</p>
</article>
<article>
   <img class="image" src="image.png"/>
   <p class="text">Text to overlay</p>
</article>
<article>
   <img class="image" src="image.png"/>
   <p class="text">Text to overlay</p>
</article>

CSS

article {
width: 33.333%;
position: relative;
float: left;
}

.image {
position: absolute;
top: 0;
left: 0;
}

.text {
z-index: 100;
position: absolute;
color: white;
font-size: 24px;
font-weight: bold;
left: 0;
bottom: 0;
}

此处不显示文本,所有图像最终都在彼此之上而不是在网格中。

当我使用相对定位时,它可以工作,但无法将文本定位在图像的底部。调整浏览器大小时,文本会四处移动。

我仔细查看了以下主题,他们似乎使用绝对定位来管理它,所以我不确定我在哪里弄错了。 https://cubicdemo.wordpress.com/

从图像中删除定位。

我不确定你想要的是什么效果,我想是这样的:

article {
  width: 33.333%;
  position: relative;
  float: left;
  text-align: center;
}
.image {
  display: block;
  width: 100%;
  height: auto;
  margin: auto;
}
.text {
  z-index: 100;
  position: absolute;
  color: white;
  font-size: 24px;
  font-weight: bold;
  left: 0;
  right: 0;
  bottom: 0;
}
<article>
  <img class="image" src="http://lorempixel.com/output/city-q-c-150-150-1.jpg" />
  <p class="text">Text to overlay</p>
</article>
<article>
  <img class="image" src="http://lorempixel.com/output/city-q-c-150-150-1.jpg" />
  <p class="text">Text to overlay</p>
</article>
<article>
  <img class="image" src="http://lorempixel.com/output/city-q-c-150-150-1.jpg" />
  <p class="text">Text to overlay</p>
</article>