How to Center a Div in CSS — The Complete Guide
Centering a div is the most Googled CSS question. Here’s every method with when to use each.
Quick Reference
| Method | Best For | Lines |
|---|---|---|
| Flexbox | Centering one or more items | 3 |
| CSS Grid | Single items or full-page centering | 3 |
| Margin auto | Block-level horizontal centering | 1 |
| Absolute transform | Unknown width/height | 2 |
| Text align | Inline/inline-block children | 1 |
1. Flexbox (Recommended)
.parent {
display: flex;
align-items: center;
justify-content: center;
}Centers child both horizontally and vertically. Works with any number of children, any sizes.
2. CSS Grid
.parent {
display: grid;
place-items: center;
}The shortest method. place-items is shorthand for align-items and justify-items.
3. Margin Auto (Horizontal Only)
.child {
width: 300px;
margin: 0 auto;
}Only works for horizontal centering. Child must have a set width.
4. Absolute Positioning
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}Works even when the child’s dimensions are unknown. Useful for modals and overlays.
5. Text-Align (Inline Children)
.parent {
text-align: center;
}Only works when the child is display: inline or display: inline-block.
Need more CSS help? Check our Flexbox guide.