2014-11-03 166 views
2

我正在嘗試將div內的一些文本垂直對齊到中心,但我無法這樣做。我試過使用顯示方法是表格和表格單元格,但這似乎不起作用。請幫忙。在div中垂直對齊文本

Fiddle

HTML:

<div class="vc_row wpb_row vc_row-fluid blunetser-banner vc_custom_1415005990938"> 
<div class="vc_col-sm-12 wpb_column vc_column_container"> 
    <div class="wpb_wrapper"> 
     <div class="vc_row wpb_row vc_inner vc_row-fluid blunet-serv-banner-row"> 
      <div class="wpb_wrapper"> 
       <div class="wpb_text_column wpb_content_element "> 
        <div class="wpb_wrapper"> 
         <p>Some text will go here</p> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 
</div> 

CSS:

.blunetser-banner { 
display: table; 
height: 300px; 
background: #eee; 
} 
.blunet-serv-banner-row { 
display: table-cell; 
vertical-align: middle; 
} 
+4

So..much ... wrappers – timo 2014-11-03 09:38:13

+0

父級應該是'display:table',直接子級'display:table-cell'。你有其他父母的孩子... – jackJoe 2014-11-03 09:38:43

+0

http://stackoverflow.com/questions/2939914/vertically-align-text-in-a-div?rq=1 – 2014-11-03 10:26:05

回答

0

因爲.blunet-serv-banner-row不是.blunetser-banne直接子,它不佔用100%的高度。

它應該是:

.vc_column_container { 
    display: table-cell; 
    vertical-align: middle; 
} 

See updated fiddle here.

1

我想你使用樣式表中的錯誤的類名?

http://jsfiddle.net/f72ocv0x/5/

.wpb_text_column { 
    display: table; 
    height: 300px; 
    background: #eee; 
} 
.wpb_wrapper { 
    display: table-cell; 
    vertical-align: middle; 
} 
2

這是這個問題我最喜歡的解決方案(簡單和很好的瀏覽器支持):

HTML

<div class="vcenter"> 
    <p>Text</p> 
</div> 

CSS

.vcenter{ //change this 
    width: 300px; 
    height: 300px; 
} 
.vcenter:before { 
    content: " "; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
} 

.vcenter :first-child { 
    display:inline-block; 
    vertical-align:middle; 
} 

小提琴:http://jsfiddle.net/u5x7ta0w/2/

因此,對於您的情況:

.wpb_wrapper{ 
    width: 300px; 
    height: 300px; 
} 
.wpb_wrapper:before { 
    content: " "; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
} 

.wpb_wrapper :first-child { 
    display:inline-block; 
    vertical-align:middle; 
} 
0

你必須給與文本的DIV中有一個行高,要是你給了DIV線高度爲300px它會在中間

.blunetser-banner { 
display: table; 
height: 300px; 
background: #eee; 
line-height: 300px; 
} 

線高度需要是相同的div

http://jsfiddle.net/f72ocv0x/6/

的高度
+1

是的,但這失敗(非常困難),如果內容使用兩行 – 2014-11-03 09:52:43

+0

爲true,但對於1行非常有用 – kaaai3 2014-11-03 09:53:30

+0

是的,我想。如果你看看我的答案,你可能會發現一個更靈活的解決方案..乾杯! (編輯:順便說一下,你不需要'display:table'來使用'line-height'來垂直對齊) – 2014-11-03 09:54:09