2014-01-30 87 views
1

我在使用CSS的DIV中垂直居中文本出現問題。我已經在SO和其他地方跟蹤了相關的答案,但似乎無法使其發揮作用。我簡單的情形是如何使用CSS在DIV中垂直居中文本?

<div class="outer"> 
    <div class="header-title"> 
     <span class="header-text">This is the title</span> 
    </div> 
</div> 

div.outer { 
    position: relative; 
    height: 200px; 
    border-style: solid; 
    border-width:1px; 

} 

div.header-title { 
    position: absolute; 
    font-size: 36px; 
    height: 100%; /* required */ 
    color: green; 
    border-style: dashed; 
    border-width:1px; 
} 

span.header-text { 
    vertical-align: middle; 
    border-style: dotted; 
    border-width:1px; 
} 

但結果(在Safari中)離開 '頭文字' spandiv的 '標題標題' 頂部:

enter image description here

+3

你的例子爲中心。怎麼了? – Morpheus

+0

烏爾提琴工作正常...你在找什麼? – UID

+1

@Morpheus:嗯。那麼它能成爲我的瀏覽器嗎?我會張貼我在Safari中看到的帽子圖像。 – orome

回答

1

您的示例顯示了一個很好的解決方法,用於在div中垂直居中元素:

display: table-cell; 
vertical-align: middle; 

所以把它添加到您的DIV + CSS:

div.header-title { 
position: absolute; 
font-size: 36px; 
height: 100%; /* required */ 
color: green; 
display: table-cell; 
vertical-align: middle; 
border-style: dashed; 
border-width:1px; 
}