4 ways to center content with CSS

CSS, Layout · Sep 28, 2021

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.

Using the grid module is very similar to flexbox and also a common technique, 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 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.

Last but not least, table centering is an older technique which you might favor when working with older browsers. It depends on the use of display: table in the container element. This allows the child element to use display: table-cell in combination with text-align: center and vertical-align: middle to center itself horizontally and vertically. You can view the Display table centering snippet for the code and examples.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • CSS Centering

    A collection of techniques for centering HTML elements in any situation using CSS.

    Collection · 5 snippets

  • Flexbox centering

    Horizontally and vertically centers a child element within a parent element using flexbox.

    CSS, Layout · Dec 30, 2020

  • Grid centering

    Horizontally and vertically centers a child element within a parent element using grid.

    CSS, Layout · Dec 30, 2020

  • Display table centering

    Vertically and horizontally centers a child element within its parent element, using display: table.

    CSS, Layout · Dec 30, 2020