2016-07-08 63 views
2

我有一個包含一些內容的div。它有一個31px的高度,裏面,按鈕有較小的高度。將內容垂直對齊到div的中間?

<div class="headerAndButton"> 
    <h3 class="h3"> 
     Click the button to the right 
     <button>click me</button> 
    </h3> 
</div> 

我有另一個標題,它沒有一個按鈕。

<div class="headerAndButton"> 
    <h3 class="h3">No button here, I only want to have this header have the same vertical alignment, height and margin as the other header</h3> 
</div> 

我想在每個div內垂直對齊<h3>文本。我曾嘗試用下面SCSS來解決這個問題:

.headerAndButton { 
    margin-bottom: $space-300; 

    h3 { 
    min-height: 31px; 
    vertical-align: bottom; 

    button { 
     margin-left: $space 
    } 
    } 
} 

vertical-align屬性沒有明顯的效果。沒有底部的文字是頂部對齊的。另一方面的文字有點低。如果我刪除按鈕,它也會變成頂部對齊。

我怎樣才能使這個標題具有相同的垂直對齊?我不擅長CSS,所以也許有更好的方法來解決這個問題。

+0

做你想做的只是垂直對齊的元素還是應該的標題標籤在同一個高度,而一個具有以下按鈕和其他不? –

+0

該按鈕位於標題的右側。我希望標題文本在它們的div內部具有相同的垂直對齊方式,這樣我就很容易在包含標題的div和跟隨它們的正文文本之間有相等的空間 – user1283776

+0

您是否有可能使用固定字體大小爲標題?還是你必須創建一個動態解決方案? –

回答

0

您可以使用display:table-cell然後vertical-align:middle來做到這一點。

JS Fiddle

(我添加邊框,所以你可以看到H3對齊)

5

你可以用幾種方法來垂直對齊的元素。例如,你可以使用新的display: flex方法:

display: flex; 
justify-content: center; 
flex-direction: column; 

Example

如果其position: absolute你的元素沒有問題,你可以使用

position: absolute; 
top: 50%; 
transform: translate(-50%, -50%); 

有來自CSS-技巧相當好的教程,名爲Centering in CSS: A Complete Guide

2
display: flex; 
justify-content: center; 
align-items: center; 

只是應用此CSS代碼上headerAndButton