Breakdown

Summary

Centering elements within their parent containers has historically been a challenging task since the dawn of web development. With the evolution of CSS, developers now have a plethora of tools to tackle this problem efficiently. This tutorial from Josh Comeau explores various approaches to centering elements, providing a comprehensive set of strategies for handling centering. The article presents trade-offs between different methods, leaving you with with a range of techniques for centering divs in CSS layouts.

Key Points

  • Auto margins (margin-left: auto; margin-right: auto;) is an old but useful technique for horizontally centering an element within its parent

  • Logical properties like margin-inline provide a modern and more internationalized way to set margins

  • Flexbox allows centering elements horizontally and vertically with justify-content and align-items

  • Fixed Positioning with inset: '0px' and margin: 'auto' can center within the viewport

  • For elements with unknown sizes, using width: fit-content; height: fit-content; along with positioning can center them

  • CSS Grid can concisely center elements with place-content: center;

  • Grid allows stacking centered elements into the same cell using grid-row/grid-column

  • Centering text itself within a block – use text-align: center;

Check out the article for an in-depth exploration and live examples - it even includes CodePens that you can play with.

CleanShot 2024-05-04 at 13.30.38@2x.png
Screenshot of a code example (source)

"I decided to create this tutorial to help you understand the trade-offs between different approaches, and to give you an arsenal of strategies you can use, to handle centering in all sorts of scenarios.