How do you center a div in CSS?

Three modern ways to horizontally and vertically center a div: Flexbox, CSS Grid, and the classic margin auto trick.

CSSFlexboxGridLayout

Overview

Centering a div is one of the most searched CSS questions of all time. The good news: modern CSS makes it easy with Flexbox or Grid. The classic "margin: auto" approach still works, but only for horizontal centering of block elements with a known width. Below are the three most practical approaches, from most recommended to least.

Key Points

  • •Flexbox is the go-to for 1D centering: center both axes with just 3 lines on the parent.
  • •CSS Grid works the same way and is especially useful when the parent is already a grid container.
  • •margin: auto centers horizontally only and requires a fixed width on the element.
  • •All three approaches center the child inside the parent. Make sure the parent has an explicit height if you want vertical centering to work.

Examples

Flexbox: center both horizontally and vertically

css
.parent {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
  height: 100vh;           /* parent must have height */
}

Most common approach. Works for any child size.

CSS Grid: one-liner with place-items

css
.parent {
  display: grid;
  place-items: center; /* shorthand for align-items + justify-items */
  height: 100vh;
}

place-items: center is the shortest way to center with Grid.

Classic margin: auto, horizontal centering only

css
.child {
  width: 400px;       /* must have a width */
  margin: 0 auto;     /* centers horizontally */
}

Only works horizontally. The child needs an explicit width.

Full example: Flexbox centering a card on the page

html
<style>
  body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    margin: 0;
    background: #0f172a;
  }
  .card {
    background: #1e293b;
    color: white;
    padding: 2rem;
    border-radius: 12px;
    width: 320px;
    text-align: center;
  }
</style>

<div class="card">
  <h2>I am centered!</h2>
  <p>Using Flexbox on the body element.</p>
</div>

Pro Tip

When in doubt, use Flexbox. It is supported in all modern browsers and handles both axes with minimal code. Grid is equally powerful and is already your answer if the parent is a grid layout.