2017-07-05 34 views
0

我通常只是使用行高来进行垂直居中,但在这种情况下,我正在处理的布局有点复杂。动态高度包装中的垂直居中文本

我把这个jsfiddle放在一起来显示我到目前为止的位置。所有CSS黑客建议使用表细胞欺骗了这一点,但我只能得到,如果包装有一个绝对高度它的工作,所以对我来说这个文本是不垂直居中:

<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

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>

+0

绝对完美的,谢谢! – Ric

-1

我也将使用柔性您的解决方案。

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

我认为这是更好地利用平移Y,它工作在更多的设备

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