SnippetCSS

Center anything, both axes

Centers any child both horizontally and vertically in two lines of CSS, using grid's place-items shorthand instead of flexbox's two rules.

Last updated

Snippetcss
.center {
  display: grid;
  place-items: center;
}

/* centers every direct child, both axes, in one declaration */

How it works

place-items is shorthand for align-items and justify-items together — on a grid container, setting it to center centers a child along both the block (vertical) and inline (horizontal) axes in that single line, where the flexbox equivalent needs both align-items: center and justify-content: center to do the same job.

This works with zero knowledge of the child's size or the container's size, which is what makes it the reliable default reached for over margin tricks or absolute positioning plus transforms — it centers correctly whether the child is 20px or 200px, and reflows correctly if either size changes later.

Edge cases to know

  • The flexbox equivalent (display: flex; align-items: center; justify-content: center;) does the identical job and is worth reaching for instead if the container already needs to be a flex context for other reasons (gap-based row/column layout, flex-wrap, etc.) — there's no need to switch a working flex container to grid just for centering.
  • If you only have ONE child and don't need a general-purpose centering utility, margin: auto on the child inside a container with a defined width/height is often simpler still — it needs no special display mode on the parent at all.
  • place-items centers every direct child independently, not the container's content as a block — with multiple children, each one centers in its own grid cell rather than the group centering together as a unit.

Related in Snippets