Centering in CSS: Every Modern Method and When Each One Breaks
"How do I center a div" survives as a joke because for a long time the honest answer was "it depends on six things you have not told me". Modern CSS reduces it to a handful of methods, each with one clear use, and one trap that none of the short answers mention: what happens when the centered thing is bigger than its container. This page catalogues the methods that remain worth using, shows which one fits which situation, and covers safe alignment so a centered dialog never loses its top edge. It belongs to Flexbox Layout Patterns in the Mastering Container Queries & Responsive Layouts guide.
Why there are still several methods
Centering is really two independent questions: along which axes, and in which layout mode the parent already is. Horizontal centering of a block with a known width has worked with margin-inline: auto since the earliest CSS. Vertical centering needed a layout mode that distributes free space in the block axis, which ordinary block flow did not do until recently. Grid and flexbox added alignment properties that do both, and the positioning model has its own answer for elements taken out of flow.
The right method is therefore the one that matches what the parent already is. Switching a parent to grid just to center one child is fine on an empty hero, but on a parent whose other children rely on block flow — margin collapsing, floats, normal wrapping — it changes more than you intended.
The complete implementation
Each numbered block below is a complete, independent centering method. They share one page so they can be compared; in practice you would use one.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Centering methods</title>
<style>
body { font: 14px/1.4 system-ui, sans-serif; margin: 1rem; display: grid; gap: 1rem; }
.box {
height: 5rem;
border: 1px dashed #94a3b8;
border-radius: 8px;
}
.item { padding: 0.5rem 0.75rem; border-radius: 6px; background: #dbeafe; color: #1e3a8a; }
/* 1. Grid: one declaration on the parent, child needs nothing. */
.grid-center { display: grid; place-items: center; }
/* 2. Flexbox: main axis with justify-content, cross axis with align-items. */
.flex-center { display: flex; justify-content: center; align-items: center; }
/* 3. Auto margins inside flex or grid: free space is absorbed equally
on both sides. Unlike 'center', this never pushes content past the
start edge when it overflows (see the safe-centering section). */
.margin-center { display: flex; }
.margin-center > .item { margin: auto; }
/* 4. Block container: align-content now works without changing display,
and margin-inline: auto centers a child that has a width. */
.block-center { align-content: center; }
.block-center > .item { width: fit-content; margin-inline: auto; }
/* 5. Out of flow: stretch the containing block edges with inset: 0,
then let auto margins split the leftover space. The element needs a
size (here fit-content) or it simply fills the container. */
.abs-parent { position: relative; }
.abs-parent > .item {
position: absolute;
inset: 0;
width: fit-content;
height: fit-content;
margin: auto;
}
</style>
</head>
<body>
<div class="box grid-center"><span class="item">1 · grid</span></div>
<div class="box flex-center"><span class="item">2 · flex</span></div>
<div class="box margin-center"><span class="item">3 · auto margins</span></div>
<div class="box block-center"><div class="item">4 · block align-content</div></div>
<div class="box abs-parent"><span class="item">5 · inset + margin</span></div>
</body>
</html>
Method 1 is the default choice for a single child: the smallest amount of CSS, no rule on the child, and it works whether the child is text, an image or a component. Method 2 is the right choice when the parent is already a flex row for other reasons. Method 3 looks redundant but is quietly the most robust, for reasons covered in the key technique section. Method 4 is new: align-content used to be ignored on block containers, and now centers their content in the block axis without switching layout modes. Method 5 replaces the older top: 50%; left: 50%; transform: translate(-50%, -50%) idiom.
The key technique: safe centering and auto margins
Every centering method distributes free space. When the child is larger than the container, the free space is negative, and "center" distributes the overflow equally on both sides. Half of the child now sits above or before the container's start edge, and because scrolling can never reach negative offsets, that half is unreachable. On a login dialog taller than a landscape phone, the heading and the first field vanish.
The alignment properties accept a safe keyword that fixes this: align-items: safe center centers while there is room and switches to start alignment as soon as centering would push content past the start edge. unsafe is the explicit opposite, and the default when neither is written behaves like unsafe in most real cases.
Auto margins get the safe behaviour for free. An auto margin absorbs positive free space and resolves to zero when free space is negative, so a child with margin: auto in a flex or grid parent is centered when it fits and start-aligned when it does not. That is why method 3 is recommended for anything that might outgrow its container — dialogs, full-screen overlays, empty states with long translated text — even though place-items: center is shorter.
Centering text is a different problem
Much of the confusion around centering comes from mixing up two operations. text-align: center does not move boxes at all; it aligns the inline content inside each line box of a block. A paragraph with text-align: center is still full width, and its lines are centered inside that width. Put a button inside it and the button is centered too, because a button is an inline-level box sitting on a line. Put a <div> inside it and nothing happens to the div's position, because block-level boxes do not sit on lines.
That distinction explains a common bug. A card title centered with text-align looks right until it wraps onto two lines, at which point each line is centered independently and the ragged, diamond-shaped result looks odd in a narrow card. If the intent was "center this block of text as a unit, with its lines left-aligned", the tool is box centering: give the heading width: fit-content and margin-inline: auto, and keep text-align: start. If the intent really was centered lines, text-wrap: balance — supported in Chrome and Edge 114, Firefox 121 and Safari 17.5 — evens out the line lengths so a two-line centered title stops looking lopsided.
Vertical centering of a single line of text inside a fixed-height box has its own old trick: setting line-height equal to the box height. It still works, and it still breaks the moment the text wraps, because the second line doubles the content height. Any of the layout methods above handle wrapping correctly, so treat the line-height trick as legacy code to replace when you touch it.
Finally, icons next to text. Centering an icon against a line of text with align-items: center on a flex row centers the icon against the line box, which includes the font's ascender and descender space, so a small icon often looks slightly low. Aligning to the first baseline with align-items: baseline, or nudging the icon with vertical-align: -0.125em in inline flow, usually looks more deliberate than geometric centering — optical alignment beats mathematical alignment for glyph-sized things.
Variation: centering a modal overlay
A modal combines several of these ideas: an out-of-flow overlay covering the viewport, a dialog centered inside it, and a guarantee that a tall dialog stays reachable. The native <dialog> element's modal form already centers itself with auto margins; the rules below make a custom overlay behave the same way.
.overlay {
position: fixed;
inset: 0;
display: grid;
/* safe keeps a tall dialog's heading on screen on short viewports */
place-items: safe center;
padding: 1rem;
overflow-y: auto; /* the overlay, not the page, scrolls */
background: rgb(15 23 42 / 0.55);
}
.overlay__dialog {
width: min(100%, 32rem);
padding: 1.5rem;
border-radius: 12px;
background: #ffffff;
color: #0f172a;
}
/* Fallback for engines without the safe keyword: auto margins
provide the same start-alignment on overflow. */
@supports not (align-items: safe center) {
.overlay { place-items: start stretch; }
.overlay__dialog { margin: auto; }
}
The @supports block is not paranoia. An engine that does not understand safe drops the entire place-items declaration, not just the keyword, and the dialog would snap to the top-left. With the fallback, those engines get auto-margin centering, which is safe by construction. For entry and exit motion on the dialog itself, Transitioning display With allow-discrete shows how to animate a centered element in and out of display: none without JavaScript, and Popover Attribute and CSS Styling covers the top-layer alternative to a custom overlay.
Browser support
Grid place-items and flexbox alignment are supported everywhere; CSS Grid dates from Chrome 57, Firefox 52 and Safari 10.1. inset and fit-content sizing are also universal in current engines, with fit-content at Chrome 46, Firefox 94 and Safari 11. The two newer pieces need care. align-content on block containers shipped across engines only recently, so pair it with a flex or grid fallback if you support older browsers. The safe alignment keyword arrived in Firefox first and in Chromium and Safari later; the @supports not (align-items: safe center) fallback shown above covers every engine that lacks it.
FAQ
What is the shortest way to center an element both ways?
Make the parent display: grid and add place-items: center. It works for any single child of unknown size and needs no rules on the child itself.
Why does my centered content get cut off at the top when it is taller than the container?
Centering splits overflow equally on both sides, so part of the content moves above the container's start edge where it cannot be scrolled to. Use the safe keyword, as in align-items: safe center, or margin: auto on the child, both of which fall back to start alignment when there is overflow.
Can I center vertically without flexbox or grid now?
Yes. align-content now applies to ordinary block containers, so align-content: center on a block with a set height centers its content vertically without changing its display type. Support is newer than flexbox and grid, so keep a fallback for older engines.
Is transform: translate(-50%, -50%) still a good centering technique?
Only for absolutely positioned elements whose size you cannot know and when you need them out of flow. It can blur text on fractional pixels and it occupies the transform property you may want for animation. inset: 0 with margin: auto does the same job without a transform when the element has a size.
Related
- Flexbox Layout Patterns — the parent guide on flex-driven layout.
- Flexbox gap and Spacing — auto margins used to push items apart rather than center them.
- Sticky Footer With Flexbox or Grid — the other classic free-space layout problem.
- min-content, max-content and fit-content — the sizing keyword that makes out-of-flow centering work.
- Starting-Style Entry Animations — animating a centered dialog as it appears.
Related articles
More pages in the same section.