2016-07-08 61 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