Skip to content

How to Center a Div in CSS — The Complete Guide

Centering a div is the most Googled CSS question. Here’s every method with when to use each.

Quick Reference

MethodBest ForLines
FlexboxCentering one or more items3
CSS GridSingle items or full-page centering3
Margin autoBlock-level horizontal centering1
Absolute transformUnknown width/height2
Text alignInline/inline-block children1

1. Flexbox (Recommended)

.parent {
  display: flex;
  align-items: center;
  justify-content: center;
}

Centers child both horizontally and vertically. Works with any number of children, any sizes.

2. CSS Grid

.parent {
  display: grid;
  place-items: center;
}

The shortest method. place-items is shorthand for align-items and justify-items.

3. Margin Auto (Horizontal Only)

.child {
  width: 300px;
  margin: 0 auto;
}

Only works for horizontal centering. Child must have a set width.

4. Absolute Positioning

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Works even when the child’s dimensions are unknown. Useful for modals and overlays.

5. Text-Align (Inline Children)

.parent {
  text-align: center;
}

Only works when the child is display: inline or display: inline-block.


Need more CSS help? Check our Flexbox guide.