动态高度换行器中的垂直居中文本



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

我已经把这个jsfiddle放在一起,以显示我到目前为止所处的位置。所有的 CSS hacks 都建议为此使用表格单元格技巧,但只有在包装器具有绝对高度的情况下,我才能让它工作,所以对我来说,这个文本不是垂直居中的:

<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。

思潮?

Flexbox 可以做到这一点...

.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
}
<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>

我认为最好使用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/

我也会为您的解决方案使用 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;
}

最新更新