January 10th, 2014

Simple vertical centering with CSS

I had an epiphany yesterday.

See the Pen Simple vertical centering with CSS by Chris Nager (@chrisnager) on CodePen.

An inline element, when set to vertical-align: middle, nested inside a block-level element causes the content in the block level element to center perfectly.

Take, for example, an image with text next to it. To vertically center that text relative to the image's height, you would need to add vertical-align: middle to the img.

Logo for ChrisNager.com This is my logo

This happens because img is an inline element. Pseudo elements also render as inline elements. Aha! So, if you were not planning on using an image next to the text, you don't need an unsemantic, empty inline element. Just use an ::after pseudo element.

<div class="vertically-centered">…</div>

.vertically-centered {
height: 256px;
&rbrace;

.vertically-centered:after {
content: "";
height: 100%;
display: inline-block;
vertical-align: middle;
&rbrace;

Simple, semantic, and IE8+ compatible.


After figuring all this out, I later found that I was not the first to think of this, but in fact similar solutions had been documented years ago. But hey, I'm proud to arrive at this on my own and glad to share it with the web design/dev community.

Twitter
© 2024 Chris Nager · Source · Follow my progress

Gatsby-built, Netlify-hosted, PageSpeed Insights-approved (💯).