Center horizontally with margin: auto
The simplest CSS centering technique — give a block element a max-width and let margin-inline: auto do the rest.
Quick implementation
.centered {
max-width: 20rem;
margin-inline: auto;
}
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: Horizontally center a block element using margin-inline: auto — no flexbox, no grid.
Technical constraints:
- The element must have an explicit max-width (or width) set for auto margins to work.
- Use margin-inline: auto (logical property) rather than margin: 0 auto for better i18n support.
- Works on any block-level or display:block element.
- Use oklch() for any demo colors, not hex or rgba().
- Include a practical example with a card component that has max-width: 40rem.
Framework variant (pick one):
A) Vanilla CSS utility class .centered that can be composed with any component.
B) React component — wraps children in a centered container, accepts maxWidth prop.
Edge cases to handle:
- Inline elements (like <span>) won't respond to auto margins — ensure display: block is set or documented.
- If the element is wider than the container it fills the container rather than overflowing.
- Works correctly in RTL layouts because margin-inline is logical.
Return CSS.
Why this matters in 2026
Despite the popularity of flexbox and grid, margin-inline: auto remains the most concise centering tool for a single block element. It requires zero container changes — just add two properties to the element itself. Modern codebases use it for constrained prose containers, centered cards, and form wrappers.
The logic
When a block element has a max-width (or explicit width) smaller than its container, the browser distributes the remaining horizontal space equally between the inline-start and inline-end margins. Setting margin-inline: auto tells the browser to calculate both of these automatically, which always results in equal halves — perfect centering.
The logical property margin-inline is equivalent to margin-left: auto; margin-right: auto in left-to-right documents, but it also works correctly in right-to-left scripts without overrides.
Accessibility & performance
There are no accessibility concerns with this technique — it is pure layout with no visual motion or interaction. Performance-wise, margin-inline: auto triggers a single layout pass and nothing else. It does not cause paint or composite layers, making it the most lightweight centering method available.