Back to More
CSS Magic
Centering Things in CSS
The oldest joke in web development — except it is actually easy now.
The One-Liner
/* Center anything, horizontally and vertically */
.parent {
display: grid;
place-items: center;
}Three lines. Works every time. No magic numbers, no transforms, no flexbox gymnastics.
All the Ways to Center
| Method | Lines | When to Use |
|---|---|---|
| grid + place-items | 3 | Best — always reach for this first |
| flexbox + margin: auto | 5 | When you need one-direction centering |
| position + transform | 6 | When the parent has no fixed height |
| text-align + line-height | 4 | Inline elements and single-line text only |
Flexbox vs Grid — Quick Decision
Use Flexbox
- One-dimensional layouts (row OR column)
- Content that should wrap naturally
- Navigation bars, toolbars, centering a single item
Use Grid
- Two-dimensional layouts (row AND column)
- Explicit placements and overlapping elements
- Page layouts, card grids, dashboards
Pro Tips
- Use
gapinstead of margin on flex/grid children — cleaner spacing. min-height: 100dvhover100vh— handles mobile browser toolbars.aspect-ratio: 1makes perfect squares without hardcoding sizes.clamp(min, preferred, max)— fluid typography without media queries.