动态高度包装中的垂直居中文本

时间:2017-07-05 11:09:53

标签: html css vertical-alignment vertical-text

我通常只使用行高来进行垂直居中,但在这种情况下,我正在努力的布局有点棘手。

我把这个jsfiddle放在一起,以显示我到目前为止的位置。所有CSS黑客都建议使用table-cell技巧,但是如果包装器具有绝对高度,我只能让它工作,所以对我来说这个文本不是垂直居中的:

<div class="wrap">
    <a href="#">
        <img src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/sample-1.jpg" />
        <span class="text"><span>Text that might span multiple lines</span></span>
    </a>
</div>

https://jsfiddle.net/fdtbvmcw/

我基本上需要的是文本,无论它跨越多少行,都坐在图像的中间。图像不能是背景图像,我无法将固定宽度或高度附加到包装器。

包装器正在模拟较大页面模板中的响应列,我需要图像保留您看到的该列的全宽。如果需要,可以在列中添加其他HTML。

思想?

3 个答案:

答案 0 :(得分:3)

Flexbox可以做到这一点......

&#13;
&#13;
.wrap {
  height: auto;
  position: relative;
  width: 50%;
}

.wrap a img {
  height: auto;
  width: 100%;
}

.wrap a span.text {
  height: 100%;
  left: 0;
  position: absolute;
  text-align: center;
  top: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrap a span.text span {
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  line-height: 1.25
}
&#13;
<div class="wrap">
  <a href="#">
    <img src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/sample-1.jpg" />
    <span class="text"><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id praesentium nihil iure amet dolore nulla totam modi </span></span>
  </a>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为最好使用translateY,它适用于更多设备

//CSS
.wrap {
  height: auto;
  position: relative;
  width: 50%;
}

.wrap a img {
  height: auto;
  width: 100%;
}

.wrap span {
  color: #fff;
  font-size: 26px;
  font-weight: bold;
  line-height: 30px;
  vertical-align: middle;
  top: 50%;
  transform: translateY(-50%);  
  display:block;
  position:absolute;
  text-align:center;
}

//HTML
<div class="wrap">
<a href="#">
  <img src="http://www.thekrausemouse.com/wp-content/uploads/2016/03/sample-1.jpg" />
  <span>Text that might span multiple lines</span>
</a>
</div>

https://jsfiddle.net/MAXXALANDER/fdtbvmcw/2/

答案 2 :(得分:-1)

我也会使用flex作为你的解决方案。

.wrap a .text {
  height: 100%;
  left: 0;
  position: absolute;
  text-align: center;
  top:0;
  display: flex; 
  display: -webkit-box;    
  display: -moz-box;       
  display: -ms-flexbox;    
  display: -webkit-flex;    
  justify-content: center;
  align-items: center;
}