Ah, the classic question! Here are all the ways to center a div:
Method 1: Flexbox (Recommended)
.parent {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 100vh; /* or any height */
}
Method 2: CSS Grid
.parent {
display: grid;
place-items: center; /* shorthand for both! */
height: 100vh;
}
Method 3: Position + Transform
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Method 4: Margin Auto (Horizontal only)
.child {
width: 200px; /* must have width */
margin: 0 auto;
}
Method 5: Flexbox with Margin
.parent {
display: flex;
height: 100vh;
}
.child {
margin: auto; /* works in both directions! */
}
When to use which:
| Method |
Use Case |
| Flexbox |
Most cases, especially with multiple items |
| Grid |
When you need 2D layout anyway |
| Position + Transform |
Overlay elements, modals |
| Margin auto |
Simple horizontal centering |
My recommendation: Use Flexbox. It's the most versatile and widely supported.
/* The magic 3 lines */
display: flex;
justify-content: center;
align-items: center;
You'll never forget this once you understand that justify is main axis and align is cross axis!