2017-07-05 31 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/