How to center a div - all the methods

Asked by Emily Chen Oct 20, 2025 beginner 2433 views
156

This is embarrassing, but I still struggle with centering divs in CSS. What are all the different ways to center a div both horizontally and vertically?

I want to understand:

  • Flexbox method
  • Grid method
  • Transform method
  • Margin auto method

Which one should I use in what situation?

Solutions

1 answer
Accepted Answer
287

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!

Answered by Alex Kumar Sep 9, 2025