将标题标记对齐到图像的中心

时间:2015-08-18 06:46:00

标签: html css css3 twitter-bootstrap-3 responsive-design

我的HTML代码如下

  <div class="col-md-3 portfolio-item">
            <a href="#">
                <img class="img-responsive" src="images/starter.jpg" alt="starter">
                <h2> Starter</h2>
            </a>
  </div>

下面是我写的CSS,它工作正常。但我想知道将h2标签垂直和水平放置到图像中心的最佳方法是什么。或者这是这样做的方式?

  .portfolio-item h2 {
      left: 100px;
      position: absolute;
      top: 45px;
  }

  .portfolio-item img {
      position: relative;
  }

3 个答案:

答案 0 :(得分:1)

如果我理解正确,答案会从评论中更新:

&#13;
&#13;
* {font-family: Segoe UI; margin: 0; padding: 0;}
.portfolio-item a {position: relative; display: block; width: 100px; height: 100px;}
.portfolio-item a img, .portfolio-item a span {position: absolute; left: 0;}
.portfolio-item a span {top: 50%; margin-top: -0.75em; width: 100px; text-align: center;}
&#13;
<div class="col-md-3 portfolio-item">
  <h2>
    <a href="#">
      <img class="img-responsive" src="http://placehold.it/100x100" alt="starter" />
      <span>Starter</span>
    </a>
  </h2>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用链接作为包含元素,然后相应地定位标题

&#13;
&#13;
* {
  font-family: Segoe UI;
  margin: 0;
  padding: 0;
}

.portfolio-item a {
  position:relative;
  display:inline-block;
}
.portfolio-item a h2 {
  position:absolute;
  text-align:center;
  top:50%;
  left:0;
  width:100%;
  transform:translateY(-50%);
  background:lightblue;
  }
&#13;
<div class="col-md-3 portfolio-item">
  <a href="#">
    <img class="img-responsive" src="http://placehold.it/100x100" alt="starter" />
    <h2> Starter</h2>
  </a>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我把h2放在一个涵盖完整100%父级的范围内。 我给了它一个显示表格单元格。

:before类确保父级被拉伸100%,以便您可以垂直居中。

<div class="col-md-3 portfolio-item">
    <a href="#">
        <img class="img-responsive" src="http://www.blackfeathers.nl/Testbeeld.jpg" alt="starter">
        <span>
            <h2> Starter</h2>
        </span>
    </a>
</div>

CSS

a {
    position: relative;
    display: block;
    text-align: center;
    }
span {
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
}
span:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
h2 {
    display: inline-block;
    vertical-align: middle;
}

Fiddle