How to Center a Div - The 3 Modern Ways (2026)
Centering a <div> used to be a meme in the CSS world because it was surprisingly hard. But in 2024, we have three clean, modern solutions. Here's how to do it properly.
Method 1: Flexbox (Most Popular)
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* Full viewport height */
}
When to use: Modern layouts, when you need to center both horizontally AND vertically.
Method 2: CSS Grid
.container {
display: grid;
place-items: center;
height: 100vh;
}
When to use: When working with grid-based layouts already.
Method 3: The Classic Margin Auto
.centered-div {
width: 300px;
margin: 0 auto;
}
When to use: Simple horizontal centering only (still works perfectly!).
margin: 0 auto. For modern full centering, use Flexbox. For grid layouts, use CSS Grid's place-items: center.
Which One Should You Use?
It depends on your project:
- Flexbox: 90% of centering cases in 2024
- CSS Grid: When your entire layout is grid-based
- Margin Auto: Quick horizontal centering (still relevant!)
Practice Challenge: Create a 400x400px div with a background color and center it in the middle of your page using all three methods.
Comments
Post a Comment