How to center a div horizontally and vertically in CSS

· Category: HTML & CSS

Short answer

The modern, recommended way is Flexbox or CSS Grid. Both allow centering with just a couple of properties on the parent container.

Steps

  1. Flexbox: Set display: flex, justify-content: center, and align-items: center on the parent.
  2. Grid: Set display: grid and place-items: center on the parent.
  3. Absolute positioning: Set position: absolute, top: 50%, left: 50%, and transform: translate(-50%, -50%) on the child.

Example

/* Flexbox */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

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

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

Tips

  • Prefer Flexbox and Grid over absolute positioning because they adapt dynamically to content size.
  • For single-axis centering, use justify-content (main axis) or align-items (cross axis).