如何在一个绝对定位的响应式图像上垂直和水平居中文本?

时间:2014-12-03 14:05:49

标签: css

我研究了很多帖子,但没有一个与我自己的情况完全相关,我不能为我的生活想出这个。我在一个绝对定位的容器内有一个响应式图像。页面上有许多这样的图像,它是图像的图库网格,但每个图像的宽度和高度都不同。

我需要图片上的链接才能阅读'查看项目'准确地垂直和水平居中。我可以通过设置图像顶部的最佳拟合%边距来手动执行此操作,但是页面上的所有图像都会占用很多代码时间,就像我说的那样,所有宽度和高度都不同。

我的基本代码看起来像这样..

<div class="item" style="position: absolute; left: 0px; top: 0px;">
  <a href="link-to-view-project-on-a-different-page.html" title="">
    <img style="width: 100%;" alt="" src="http://placekitten.com/600/400">
    <h2>View Project</h2>
  </a>
</div>

2 个答案:

答案 0 :(得分:0)

根据浏览器支持,您可以使用具有绝对定位的css转换。 E.g:

h2 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

Demo

如果浏览器支持是个问题,您可以使用负边距来获得类似的结果。 E.g:

h2 {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -5px; /* This value should be half the height of the h2 element */
  margin-left: -5px; /* This value should be half the width of the h2 element */
}

答案 1 :(得分:0)

这是一个工作小提琴http://jsfiddle.net/xnjy0dar/

基本上你需要一个包装图像和h2元素。将包装器设置为角落中的绝对位置或您希望图像显示的位置。将h2也设置为绝对位置。包装器将与图像一样大。现在就像这样定位h2。

.image1 {
    top: 0;
    left: 0;
}
.image2 {
    top: 200px;
    left: 0;
}
.image1, .image2 {
    position: absolute;
    text-align: center;
}
.image1 h2, .image2 h2 {
    position: absolute;
    display: block;
    width: 100%;
    top: 50%;
    margin-top: -14px;
    margin-bottom: 0;
    left: 0;
}

它是margin-top的原因:-14px是为了补偿h2的高度。 14px是示例中h2高度的一半,因此请相应调整。

这是html:

<div class="image1">
    <img src="http://placehold.it/350x150" />
    <h2>View Project</h2>
</div>
<div class="image2">
    <img src="http://placehold.it/150x250" />
    <h2>View Project</h2>
</div>