Reputation: 699
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. But I still need help to align two lines inside a 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. Maybe playing with the padding or some relative positioning would be the answer. What's the best way to vertically center this text content?
Upvotes: 1
Views: 1189
Reputation: 67738
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):
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)
.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>
Upvotes: 2