Here are 3 very good techniques for vertically centering a child within a container - even when you don't know the height of the child element. The first 2 come from this CSS-tricks article
Markup (for all methods):
<div class="block">
<div class="centered">
Some text
</div>
</div>
Solution #1: CSS tables method (FIDDLE)
CSS:
/* This parent can be any width and height */
.block {
display: table;
width: 100%;
background: orange;
height: 300px;
}
.centered {
display: table-cell;
text-align: center;
vertical-align: middle;
background: pink;
}
Solution #2: Pseudo ('Ghost') element method (FIDDLE)
CSS:
/* This parent can be any width and height */
.block {
text-align: center;
background: orange;
height: 300px;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
background: pink;
}
Solution #3: Flexbox (FIDDLE)
(Relevant) CSS:
.block {
background: orange;
height: 300px;
display: flex;
align-items: center;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…