2011-11-08 106 views
0

我有一些簡單的css,旨在顯示其父母div中間(垂直)的段落元素。嘗試垂直對齊段落元素

我的問題:段落元素沒有垂直對齊,它始終位於頂部。該解決方案只能在Safari上運行(特別是iPad的Safari版本)。

你知道如何讓我的段落元素垂直對齊中間?

<html> 
<head> 

    <style type="text/css"> 
    <!-- 
     .ButtonBox { 
      cursor: pointer; 
      vertical-align: middle; 
      text-align: center; 
      background-color: blue; 
      height: 200px; 
     } 

     .buttonBoxContainer { 
      cursor: pointer; 
     } 
    --> 
    </style> 
</head> 
<body> 

    <div class="ButtonBox"> 
     <p class="buttonBoxContainer">Press Me</p> 
    </div> 

</body> 
</html> 

回答

2

如果你的盒子將永遠有一個靜態的高度,你可以使用的line-height居中段落元素,如圖所示here

如果它不是靜態的,最好的解決方案(以我的經驗)是使用javascript。

<html> 
<head> 
    <style> 

     .ButtonBox { 
      cursor: pointer; 
      vertical-align: middle; 
      text-align: center; 
      background-color: blue; 
      height: 200px; 
      color: #fff; 
     } 

     .buttonBoxContainer { 
      cursor: pointer; 
      line-height: 200px; 
     } 
    </style> 
</head> 
<body> 

    <div class="ButtonBox"> 
     <p class="buttonBoxContainer">Press Me</p> 
    </div> 

</body> 
</html> 
+0

哇,嚴重的是,我認爲可能有一個CSS3的解決方案? –

+1

有一個CSS 3解決方案。您可以使用CSS 3的靈活框佈局模塊。它在IE中不受支持。詳情請看這裏:http://caniuse.com/#search=flexible http://flexiejs.com/playground/有一個漂亮的工具來玩定位。 – martineno

+0

@martineno我建議這是一個答案,假設即不需要支持;它完全由iOS Safari支持。我很慚愧我沒有想到這個......用css2編碼太多年了。 –