Back to More
CSS Magic

Centering Things in CSS

The oldest joke in web development — except it is actually easy now.

The One-Liner

/* Center anything, horizontally and vertically */
.parent {
  display: grid;
  place-items: center;
}

Three lines. Works every time. No magic numbers, no transforms, no flexbox gymnastics.

All the Ways to Center

MethodLinesWhen to Use
grid + place-items3Best — always reach for this first
flexbox + margin: auto5When you need one-direction centering
position + transform6When the parent has no fixed height
text-align + line-height4Inline elements and single-line text only

Flexbox vs Grid — Quick Decision

Use Flexbox

  • One-dimensional layouts (row OR column)
  • Content that should wrap naturally
  • Navigation bars, toolbars, centering a single item

Use Grid

  • Two-dimensional layouts (row AND column)
  • Explicit placements and overlapping elements
  • Page layouts, card grids, dashboards

Pro Tips

  • Use gap instead of margin on flex/grid children — cleaner spacing.
  • min-height: 100dvh over 100vh — handles mobile browser toolbars.
  • aspect-ratio: 1 makes perfect squares without hardcoding sizes.
  • clamp(min, preferred, max) — fluid typography without media queries.