How to center div vertically inside of absolutely positioned parent div
Employ flexbox, the Swiss Army knife of CSS, to vertically center your content. By setting the parent div
to display: flex;
and align-items: center;
, the child div
is nestled right at the center, vertically. And yes, it's that simple!
Snippet:
Centering with CSS transform
If you're targeting yesteryear's browsers such as IE9 that don't support flexbox, get out your CSS toolbox and pull out transform.
Snippet:
In this scenario, using top: 50%;
and left: 50%;
positions the element halfway down and across the referring box respectively. The transform: translate(-50%, -50%)
then counteracts any misplacement, fixing the content in the center.
Dealing with inline-block elements
Sometimes, the situation calls for working with the good old inline-block elements. Here, you'll find salvation in the vertical-align: middle;
property.
Snippet:
Using font-size: 0;
on the parent gets rid of whitespace gaps, while setting the font size back on the child restores text visibility. Please note: the vertical-align
property is only applicable to inline-level elements, not blocks or boxes. It's not for everyone!
Other techniques for alignment
The Absolute Positioning trick
Give div
an absolute position, and manage offsets on all directions.
Snippet:
Transform with Perspective
Graphics can get blurry with transform, triggering OCD in many. perspective(1px)
can improve rendering.
Snippet:
Gaps and Inline-block layouts
To remove the gap between inline-block elements caused by whitespace in the HTML, set the font-size
of the parent to zero.
Snippet:
Was this article helpful?