Home / Snippets / Layout /

Center with grid + place-items

Two lines of CSS. Perfectly centered. Any content.

Centered
Widely Supported
layoutno-js

Quick implementation

.centered {
  display: grid;
  place-items: center;
  min-height: 100dvh; /* or any height */
}

Prompt this to your LLM

Includes role, constraints, two framework variants, and edge cases to handle.

You are a senior frontend engineer building a centered layout.

Goal: Center any content both horizontally and vertically using CSS Grid — no JavaScript.

Technical constraints:
- Use display: grid with place-items: center (shorthand for align-items + justify-items).
- Set min-height to ensure the container has vertical space (100dvh for full viewport).
- Use oklch() for any color values, not hex or rgba().
- The centered content should be sized by its own content, not stretched.

Framework variant (pick one):
A) Vanilla HTML + CSS only.
B) React component — accept children to center and an optional minHeight prop.

Edge cases to handle:
- Content wider than the container should not overflow horizontally.
- Multiple children will each be centered in their own grid cell — use a wrapper if grouping is needed.
- On very small viewports, add padding to prevent content from touching edges.

Return HTML + CSS.

Why this matters in 2026

Centering used to be CSS's most infamous problem. Developers stacked transforms, table-cell hacks, and flexbox incantations. place-items: center on a grid container does it in two lines with zero side effects. It centers horizontally and vertically, works for any content size, and needs no knowledge of the child's dimensions.

The logic

display: grid creates a grid context. place-items: center is shorthand for align-items: center (vertical) and justify-items: center (horizontal). Unlike flexbox centering, grid centering does not stretch the child to fill the container — the child stays at its intrinsic size. The min-height gives the container vertical space for the centering to be visible.

Accessibility & performance

This technique is purely visual — it does not affect DOM order or screen reader behavior. Performance is identical to any other grid layout: the browser resolves sizes in a single layout pass. For full-viewport centering (error pages, loading screens), use 100dvh instead of 100vh to account for mobile browser chrome.