
Choose a centering technique based on what you are aligning: an entire box, text within a line, or an overlay inside a positioned container.
1. Center a box with Flexbox
Use justify-content on the main axis and align-items on the cross axis. Give the container a meaningful height when vertical centering is required.
.parent { display: flex; justify-content: center; align-items: center; min-height: 12rem; }2. Center a single line of text
Use text-align: center for horizontal centering. Matching line-height to a fixed height can center a single line, but does not work well if the text wraps.
3. Center an overlay with translate
Position its top-left corner at 50% of the parent and translate it by half its own size. See CSS transforms.
.parent { position: relative; }
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }4. Use a negative margin for a known size
For an absolutely positioned item with a known size, negative margins of half its width and height also work. This approach becomes brittle when the content changes.
5. Center with Grid
Use place-items: center to center grid items on both axes.
.parent { display: grid; place-items: center; min-height: 12rem; }6. Align an inline image with text
Use vertical-align on the inline image. middle uses the baseline and x-height of the containing line rather than centering a block in its parent.
.caption img { vertical-align: middle; }7. Use table-cell alignment in an older layout
A table cell can use vertical-align: middle. For a new layout, use Flexbox or Grid unless you are styling an actual table.
8. Center an inline image horizontally
Use text-align: center on its parent. If the image is a block, use margin-inline: auto when it is narrower than its container.
9. Align a checkbox and its label
Use a real label linked to the checkbox. Inline Flexbox can align its contents and its text, including when a label spans more than one line.
.option { display: inline-flex; align-items: center; gap: .5rem; }10. Center within the viewport
Put place-items: center on a container with a viewport-based minimum height. A minimum lets tall content remain reachable as the user zooms.
.viewport { min-height: 100vh; min-height: 100dvh; display: grid; place-items: center; }