Centering

Centering elements has historically been one of the most frustrating tasks for web developers. Depending on whether you are dealing with text, a single block, or multiple items and whether you need horizontal or vertical alignment the solution changes.

With modern CSS, specifically Flexbox and Grid, the "hacks" of the past are gone. We can now achieve perfect centering with just a few lines of code.

1. Horizontal Centering

1.1 Centering Text

To center text inside a block-level element (like a <p>, <h1>, or <div>), we use the text-align property.

Code Block Loading...

1.2 Centering Blocks with Flexbox

The most robust modern way to center any child element (like a <div> inside a section) is to make the parent a flex container.

Code Block Loading...

1.3 The Classic "Margin Auto" Method

If you aren't using Flexbox, you can center a block element by giving it a specific width and setting its horizontal margins to auto.

Code Block Loading...

2. Vertical Centering

In the past, vertical centering required complex table-cell hacks. Today, we simply use the align-items property on a Flex container.

Code Block Loading...

3. Perfect Centering (Horizontal & Vertical)

To center an element perfectly in the middle of its container, you can combine Flexbox properties or use the ultra-concise CSS Grid method.

Interactive Perfect Center Demo

Key Takeaways

  • For Text: Use text-align: center. It only works on inline or inline-block content within a block-level parent.
  • For Modern Layouts: Flexbox is the standard. Use justify-content: center for horizontal and align-items: center for vertical alignment.
  • The Grid Shortcut: For absolute centering of a single child, display: grid and place-items: center is the shortest and cleanest code possible.
  • Don't Forget Height: Vertical centering only works if the parent container has a defined height (like height: 100vh or height: 400px).
  • Margin Auto: Use this for simple block centering when you don't want to turn the parent into a flex/grid container.