Home / Snippets / Layout /

Center unknown-size element

Perfectly center any element on both axes using CSS grid — regardless of content size.

Short
Longer content here
Widely Supported
layoutno-js

Quick implementation

.center-unknown {
  display: grid;
  place-items: center;
  min-height: 12rem;
}

Prompt this to your LLM

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

You are a senior frontend engineer writing a CSS layout utility library.

Goal: Center an element of completely unknown dimensions — both horizontally and vertically — inside a container.

Technical constraints:
- Use display: grid with place-items: center on the container.
- The child must not have any fixed width or height set — it should size to its content.
- Works for single-line text, multi-line text, images, and arbitrary components.
- Use oklch() for any demo colors, not hex or rgba().
- The container should have a min-height so it is visible when content is short.

Framework variant (pick one):
A) Vanilla CSS utility class .center-unknown applied to the container.
B) React component — wraps children in a centered container, accepts minHeight prop.

Edge cases to handle:
- Multiple children: place-items centers each child in its own grid cell — document this behavior.
- The child should not stretch to fill the container (use place-items: center, not align-items: stretch).
- Works inside flex children, grid cells, and block flow.

Return CSS.

Why this matters in 2026

Centering unknown-size content used to require hacks involving position: absolute and negative margins. Today, display: grid; place-items: center solves it in two lines. It is the go-to solution for modal overlays, empty states, loading spinners, and hero sections where the content dimensions change at runtime.

The logic

Setting display: grid on the container turns it into a single-cell grid. place-items: center is shorthand for align-items: center; justify-items: center, which centers the child in the grid cell on both the block and inline axes. Because the child sizes to fit its content (no implicit stretching), it occupies exactly as much space as it needs — centered perfectly regardless of length.

A min-height on the container ensures there is space to center into even when content is empty or very short.

Accessibility & performance

This technique has no accessibility implications — it is purely visual layout. Performance-wise, grid layout is resolved in a single pass by the browser's layout engine. There are no reflows triggered by content size changes after initial render. For modals and overlays, pair this with inset: 0; position: fixed on the container to cover the full viewport.