2014-08-28 81 views
-1

我想垂直居中我的div中的文本,但vertical-align:middle不工作。在絕對定位的div中垂直對齊文本

這是我的CSS:

body,html { 
    height:100%; 
    min-height:100%; 
} 
#container { 
    position:relative; 
    width:300px; 
    height:70%; 
    background:red; 
} 

#box { 
    position:absolute; 
    bottom:30px; 
    background:yellow; 
    height:20%; 
    vertical-align:middle; 
    width:100%; 
    text-align:center; 
} 

這是我的html:

<div id="container"> 
    <div id="box"> 
     <p>text</p> 
    </div> 
</div> 

我試圖從%上邊距,但它不是最好的解決辦法。這裏是我的在線版本:http://jsfiddle.net/f2qf031h/

回答

0

試試這個代碼,這樣做是Flexbox的佈局

#box { 
    position: relative; 
    top:50%; 
    transform: translateY(-50%); 
    background:yellow; 
    height:20%; 
    width:100%; 
    display: table; 
    overflow: hidden; 
    text-align:center; 
} 
+0

我想中心的絕對定位的div,而不是整個DIV中的文本。 – user1452062 2014-08-28 11:09:51

+0

請參閱編輯版本的答案:) – 2014-08-28 11:15:11

1

的一種方式。

通過設置:

#box { 
    ... 
    display:flex; 
} 

#box p{ 
    align-self:center; 
    text-align:center; 
    width:100%; 
} 

的jsfiddle:http://jsfiddle.net/f2qf031h/2/