Home / Snippets / Layout /

Center utility

Constrain content to a readable width and center it horizontally.

Centered content

This content is constrained to a max-width and centered with margin-inline: auto. On narrow viewports, the padding-inline keeps it from touching the edges. Simple, robust, universal.

Widely Supported
layoutno-js

Quick implementation

.center {
  max-width: var(--center-max, 60rem);
  margin-inline: auto;
  padding-inline: var(--center-gutter, 1.5rem);
}

/* Narrow variant for text-heavy pages */
.center--narrow {
  --center-max: 42rem;
}

/* Wide variant for dashboards */
.center--wide {
  --center-max: 80rem;
}

Prompt this to your LLM

Includes role, constraints, and edge cases to handle.

You are a senior frontend engineer building a layout utility.

Goal: A reusable .center utility that constrains content to a max-width and centers it horizontally.

Technical constraints:
- Use max-width with a CSS custom property --center-max (default 60rem).
- Use margin-inline: auto for horizontal centering.
- Use padding-inline with a custom property --center-gutter (default 1.5rem) so content never touches viewport edges.
- Provide variants: .center--narrow (42rem) for article text, .center--wide (80rem) for dashboards.
- Do NOT use width: 100% — max-width alone handles responsiveness.

Edge cases:
- Content should never overflow on narrow viewports.
- Nested .center elements should not compound padding.
- Works with block and flex/grid containers as children.

Why this matters in 2026

The center utility is the most-used layout primitive on the web. Every page needs it — articles, dashboards, marketing pages. The combination of max-width and margin-inline: auto has been the correct approach for over a decade, but wrapping it in a utility with custom property hooks makes it truly reusable. No more ad-hoc width constraints scattered across your stylesheet.

The logic

max-width sets an upper bound — the element can be narrower but never wider. margin-inline: auto distributes remaining horizontal space equally on both sides, centering the element. padding-inline adds a gutter so content doesn't slam against viewport edges on mobile. Custom properties let consumers adjust the max-width and gutter without writing new CSS.

Accessibility & performance

Constraining content width directly improves readability — research shows 45–75 characters per line is optimal. The center utility enforces this naturally for text-heavy pages. Zero performance overhead: the browser resolves max-width and margin: auto in a single layout pass with no reflows.