SyntaxStudy
Sign Up
css

How to Center a Div

Center a div element horizontally and/or vertically using modern CSS.

Centering in CSS has multiple approaches. The best modern solution is Flexbox or Grid.

Method 1: Flexbox (Recommended)

Apply flexbox to the parent container:

Method 2: CSS Grid

Use place-items: center on the parent.

Method 3: Absolute Positioning

Use position: absolute with transform: translate(-50%, -50%).

When to use each

  • Flexbox — best for single items or rows/columns of items
  • Grid — best for two-dimensional layouts
  • Absolute — use when you need to center over a specific positioned parent
Example
/* Method 1: Flexbox */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

/* Method 2: Grid */
.parent {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

/* Method 3: Absolute */
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}