CSSIntermediate
How to center an element horizontally and vertically in CSS?
Method 1: Flexbox (Recommended)
.parent {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
}
Clean and intuitive — the go-to approach in modern development.
Method 2: CSS Grid
.parent {
display: grid;
place-items: center; /* shorthand for justify-items + align-items */
}
place-items: center is the most concise option, great when you're already using Grid layout.
Method 3: position + transform
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
No need to know the child's dimensions — great for modals and overlays.
Method 4: margin: auto (horizontal only)
.child {
width: 200px;
margin: 0 auto; /* horizontal only, vertical has no effect */
}
Only centers horizontally, and the child must have a defined width.
Comparison
| Method | Horizontal | Vertical | Needs Size | Recommended |
|---|---|---|---|---|
| Flexbox | ✅ | ✅ | ❌ | ⭐⭐⭐ |
| Grid | ✅ | ✅ | ❌ | ⭐⭐⭐ |
| position + transform | ✅ | ✅ | ❌ | ⭐⭐ |
| margin: auto | ✅ | ❌ | ✅ | ⭐ |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
