4 ways to center content with CSS

Flexbox
Using flexbox to vertically and horizontally center content is usually the preferred method. All it takes is three lines of code in the container element to set display: flex
and then center the child element vertically and horizontally using align-items: center
and justify-content: center
respectively. You can view the Flexbox centering snippet for the code and examples.
Grid
Using the grid module is very much similar to flexbox and is also quite common, especially if you are already using grid in your layout. The only difference from the previous technique is the display
which is set to grid
instead. You can view the Grid centering snippet for the code and examples.
Transform
Transform centering uses, as the name implies, CSS transforms to center an element. It depends on the container element having a position: relative
, allowing the child element to utilize position: absolute
to position itself. Then left: 50%
and top: 50%
are used to offset the child element and transform: translate(-50%, -50%)
to negate its position. You can view the Transform centering snippet for the code and examples.
Table
Last but not least, table centering is an older technique which you might favor when working with older browsers. It depends on the container element having a display: table
, allowing the child element to utilize display: table-cell
in combination with text-align: center
and vertical-align: middle
in order to center itself horizontally and vertically. You can view the Display table centering snippet for the code and examples.
Image credit: garrett parker on Unsplash
Recommended snippets & collections
CSS Centering
Snippet collectionA collection of techniques for centering HTML elements in any situation using CSS.
What are CSS variables and where can I use them?
CSS, Article
Learn how CSS custom properties (CSS variables) work and what you can use them for in your code and designs.
Typographic scale basics
CSS, Article
Typography might seem intimidating, but you can quickly and easily create a simple typographic scale with this basic technique.
Flexbox Cheat Sheet
CSS, Article
Flexbox allows you to create fluid layouts easily. If you find yourself constantly looking up the syntax or how it work, this handy cheatsheet is all you need.