How to center elements in CSS reliably comes down to a short list of methods: flexbox and grid centre with one or two declarations, auto margins centre a block that has a definite width, and an absolutely positioned box can be pinned to the middle with a transform.
The previous lesson in this module covered "Why Does z-index Misbehave and How Do Stacking Contexts Rule It?", and the next lesson in this module is about "How Do You Build Card Rows and Hero Sections That Reuse Well?".
How do you centre text and inline content?
Text and other inline-level content are centred with text-align: center on their block parent. This affects inline boxes inside that block, so it centres a heading, a paragraph, or a run of text inside a link. It does nothing to a block-level child, which is the usual reason beginners report that text alignment did not work on their card.
Inline images are centred by the same declaration, and the equivalent that works on an image element regardless of what its parent is doing is to make it a block and give it auto inline margins.
<figure class="poster">
<img class="poster__image" src="harbour.jpg" alt="Fishing boats moored in a harbour at dawn"
width="800" height="533">
<figcaption class="poster__caption">Berths four and five at first light</figcaption>
<span class="poster__badge">New</span>
</figure>
<p class="notice">Tickets for the morning crossing close at six.</p>
.poster__caption {
text-align: center;
}
.poster__image {
display: block;
margin-inline: auto;
}
.notice {
width: min(32rem, 100% - 2rem);
margin-inline: auto;
}
The caption sits under a centred image, and the notice is a block with a definite width, so its auto inline margins split the leftover space and leave it in the middle. That works only because the width is definite: if the width were auto the paragraph would already fill the space and there would be nothing to distribute.
How do flexbox and grid centre things?
In a flex container, justify-content distributes the items along the main axis and align-items aligns them across the cross axis. Setting both to center centres the items within the container.
<div class="player">
<button class="play" type="button" aria-label="Play the clip">
<svg viewBox="0 0 24 24" width="32" height="32" aria-hidden="true">
<path d="M8 5v14l11-7z" fill="currentColor"></path>
</svg>
</button>
</div>
.player {
display: flex;
align-items: center;
justify-content: center;
aspect-ratio: 16 / 9;
background: #101828;
}
.play {
display: grid;
place-items: center;
width: 4.5rem;
height: 4.5rem;
border: 0;
border-radius: 50%;
background: #ffffff;
color: #101828;
}
Grid offers the same result through place-items: center, which sets alignment and justification for the items inside their areas. The distinction that trips people up is between items and tracks. place-items centres each item inside the cell it occupies, while place-content centres the track grid itself inside the container. If your grid has one track that fills the container, the two produce identical results, but they diverge as soon as the tracks are smaller than the box.
One more flexbox subtlety: centring a single item that has flex: 1 looks broken, because the item has already absorbed all the free space and justify-content has nothing left to distribute. Give the item a definite width or a max-width before trying to centre it.
How do you centre an absolutely positioned box?
Absolute positioning gives you a reliable two-step method. Set inset: 0 so the box stretches to its containing block, then centre its content with grid or flex.
<div class="overlay">
<div class="overlay__panel">
<h2 class="overlay__title">Choose a berth</h2>
<p>Berths four to nine are free this morning.</p>
</div>
</div>
.overlay {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: rgb(16 24 40 / 0.6);
}
.overlay__panel {
background: #ffffff;
padding: 1.5rem;
border-radius: 12px;
max-inline-size: 28rem;
}
The alternative is the transform method, which centres a box of any size without needing to know that size in advance. The offsets move the box's left and top edges to the midpoint of the containing block, and the transform then pulls it back by half of its own width and height, because translate percentages are measured against the element's own box.
.poster {
position: relative;
}
.poster__badge {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Reach for the transform method when the box is a single element sitting on top of something else. Reach for the inset-and-grid method when the box is a full-screen layer with content inside it, because the layer then also handles the backdrop.
How do you centre a modal dialog?
The native dialog element handles the hard parts of a modal. Calling showModal() on it puts it in the top layer, moves keyboard focus into it, and makes the rest of the page inert, which is behaviour that a hand-built overlay with a high z-index does not give you for free.
<dialog class="sheet" aria-labelledby="sheet-title">
<h2 id="sheet-title">Delete this project?</h2>
<p>The archive can be restored for thirty days.</p>
<form method="dialog">
<button value="cancel">Keep it</button>
<button value="confirm">Delete</button>
</form>
</dialog>
.sheet {
margin: auto;
border: 0;
border-radius: 12px;
padding: 1.5rem;
max-inline-size: min(32rem, 92vw);
}
.sheet::backdrop {
background: rgb(16 24 40 / 0.55);
}
A modal dialog is centred by the user-agent stylesheet, so as soon as you add your own width you should keep margin: auto to preserve it. The ::backdrop pseudo-element covers the area behind the dialog and can be styled like any other pseudo-element, which is where the dimmed overlay colour belongs.
Which centring method should you reach for?
| Situation | Method | Key detail |
|---|---|---|
| A paragraph or heading | text-align: center | Applies to inline content inside the block |
| A block with a known width | margin-inline: auto | The width must be definite |
| One item in a flex or grid row | place-items or justify-content plus align-items | An item with flex: 1 has no free space to share |
| A badge on top of a picture | left and top at 50% with a translate transform | Works without knowing the badge size |
| A full-screen layer with content | inset: 0 with grid centring | The layer also paints the backdrop |
| A modal window | The dialog element | Focus handling and inertness come free |
The short version
- Inline content is centred with
text-align:center. - A block with a definite width is centred with
margin-inline:auto. - Flexbox and grid centre items with
place-items:center or the matching pair of properties. - Auto margins centre a flex item on both axes at once.
- An absolutely positioned box centres with
inset: 0plus grid, or with a translate transform. - Percentage translations are measured against the element's own size, not the container.
- The native dialog element gives you centring, focus management and an inert page in one element.
Try it yourself: take the player markup and centre the play button three different ways. First set display: flex on the player, then replace it with display: grid; place-items: center and confirm the button stays put, then switch the button to position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%) and make the player position: relative so it has an anchor. Finish by adding a dialog to the page, opening it with showModal() and confirming that the background cannot be clicked while it is open.