如何在网格中的图像上定位文本

时间:2015-06-16 15:01:50

标签: html css css-position

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

现在从在线浏览看起来这样做的方式是这样的:

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/

1 个答案:

答案 0 :(得分:1)

从图像中删除定位。

我不确定你对我的影响恰恰是因为我想象它是这样的:

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

相关问题