Depending on the layout requirements, use one of these methods to center content vertically:
- Vertical Align (Pseudo-element): Use a pseudo-element (
:after) on the parent with vertical-align: middle and height: 100%, and set the child to display: inline-block with vertical-align: middle. - Transform (Dynamic Height): Use
position: absolute with top: 50% and transform: translate(0, -50%) (or translate(-50%, 0) for horizontal) to offset the element by its own height. - Absolute Positioning (Fixed Height): Set the parent to
position: relative, the child to position: absolute with top: 50%, and apply a negative margin-top equal to half of the element's height. - Flexbox (Dynamic Height): Set the parent to
display: flex and align-items: center.
/* Vertical Align */
.parent { height: 200px; }
.parent:after { display: inline-block; width: 0; height: 100%; vertical-align: middle; content: ''; }
.parent .child { display: inline-block; vertical-align: middle; }
/* Transform */
.parent { position: relative; height: 200px; }
.parent .child { position: absolute; top: 50%; transform: translate(0, -50%); }
/* Absolute Positioning */
.parent { position: relative; }
.child { position: absolute; top: 50%; height: 200px; margin-top: -100px; }
/* Flexbox */
.flex-v-center { display: flex; align-items: center; }