[英]Vertically align two lines of text inside a div
Before this post I read couple of articles on the topic and I'm already aware of some of the used tricks for vertical align - the line-height for single line of text, the display:table for couple of divs and Flexbox in CSS3.在这篇文章之前,我阅读了几篇关于这个主题的文章,我已经知道一些垂直对齐的使用技巧——单行文本的行高、几个 div 的 display:table 和 CSS3 中的 Flexbox。 But I still need help to align two lines inside a div:
但我仍然需要帮助来对齐 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>
As you can see I already have a flexbox container and to use display:table will need an extra div.如您所见,我已经有了一个 flexbox 容器,要使用 display:table 需要一个额外的 div。 Maybe playing with the padding or some relative positioning would be the answer.
也许玩填充或一些相对定位将是答案。 What's the best way to vertically center this text content?
垂直居中此文本内容的最佳方法是什么?
Changed answer after comment:评论后更改答案:
Add this to .key
to also make it a flex container which centers its contents above each other (the already existing text-align: center
does the horizontal text-centering):将此添加到
.key
也使其成为一个 flex 容器,它的内容彼此居中(已经存在的text-align: center
执行水平文本居中):
display: flex;
flex-direction: column;
justify-content: center;
(Note: Since everything is white and therefore remains invisible, I added a black background to the .key
elements) (注意:由于一切都是白色的,因此保持不可见,我在
.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.