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)

CSS
.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

CSS
.container {
  display: grid;
  place-items: center;
  height: 100vh;
}

When to use: When working with grid-based layouts already.

Method 3: The Classic Margin Auto

CSS
.centered-div {
  width: 300px;
  margin: 0 auto;
}

When to use: Simple horizontal centering only (still works perfectly!).

💡 Pro Tip: For simple horizontal centering, use 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

Popular posts from this blog

5 JavaScript Console Methods You're Not Using (But Should Be)

Build a Simple Calculator with HTML, CSS & JavaScript