在这篇文章之前我读了几篇关于这个主题的文章,我已经知道了一些用于垂直对齐的技巧 - 单行文本的行高,显示:几个div的表和CSS3中的Flexbox。但是我仍然需要帮助来对齐div中的两行:
.keys {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
align-items: center;
min-height: 70vh;
}
.key {
border: 0.1rem solid white;
margin: 1rem;
width: 5rem;
height: 5rem;
padding: 0.5rem 0;
text-align: center;
color: white;
}
kbd {
display: block;
}

<div class="keys">
<div class="key" data-key="65"><kbd>A</kbd><span class="sound">text</span></div>
<div class="key" data-key="83"><kbd>S</kbd><span class="sound">text</span></div>
<div class="key" data-key="68"><kbd>D</kbd><span class="sound">text</span></div>
<div class="key" data-key="70"><kbd>F</kbd><span class="sound">text</span></div>
</div>
&#13;
正如您所看到的,我已经有了一个flexbox容器并且使用display:table将需要一个额外的div。也许玩填充或一些相对定位将是答案。什么是垂直居中此文字内容的最佳方式?
答案 0 :(得分:1)
评论后更改了答案:
将此添加到.key
以使其成为一个灵活容器,将其内容集中在彼此之上(已存在的text-align: center
执行水平文本居中):
display: flex;
flex-direction: column;
justify-content: center;
(注意:由于一切都是白色的,因此保持不可见,我在.key
元素中添加了黑色背景)
.keys {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
align-items: center;
min-height: 70vh;
}
.key {
display: flex;
flex-direction: column;
justify-content: center;
border: 0.1rem solid white;
margin: 1rem;
width: 5rem;
height: 5rem;
padding: 0.5rem 0;
text-align: center;
color: white;
background: black;
}
kbd {
}
<div class="keys">
<div class="key" data-key="65"><kbd>A</kbd><span class="sound">text</span></div>
<div class="key" data-key="83"><kbd>S</kbd><span class="sound">text</span></div>
<div class="key" data-key="68"><kbd>D</kbd><span class="sound">text</span></div>
<div class="key" data-key="70"><kbd>F</kbd><span class="sound">text</span></div>
</div>