How to vertically align content with CSS

Learn how you can easily center your content with modern CSS. I'll show you the old way and then how you can use Grid, Flexbox and then the latest 'block level'positioning.

Vertically aligning content has gotten much easier with the latest additions to CSS. Gone are the days of using transform: translate(); with absolute positioning 🤢.

The old

This example uses transform: translate() with absolute: position;. This method causes issues with the DOM flow as well as a z-index ordering problem; note that the borders are overlapping here. I've also had to use another div to wrap the content of the container to ensure all content is centered. This implementation is longer to write, maintain, and prone to other issues as you build out your design/page:

GRID

CSS Grid is ideally used for multi-dimensional layouts, and focuses on content placement (you can control content layout on both the X and Y axis). The use of Grid here may be overkill (I use this for my homepage hero but I'm thinking I may change it). I think that if you're using Grid, then it should be for something more creative; maybe you have a design that overlaps an image with text. Grid will easily allow this to be done with the use of columns and rows where you can get really creative with different screen sizes.

Flexbox

Flexbox focuses on content flow rather than content placement, you have to think about left/right up/down flowing content (this can be reversed too). I feel that there's more to think about when using Flexbox; you need to set the direction, consider if there's to be any wrapping, and then justify the content to the center. It shares the benefits of Grid when it comes to responsive design but with some placement restrictions.

Block level alignment

I really like the simplicity of this approach: align-content: center; and display: block.

Wrap up

The purpose of this post was to showcase different ways to vertically center content using modern CSS. Browser support is solid for all implementations and I would suggest using what works best for your content/design.

I believe it's good to make use of the latest CSS features in your websites/applications to help reduce the amount of CSS you have to maintain as the newer implementations are more reliable and scalable.