01

Center horizontally with margin: auto

Moves the child to the horizontal middle. It does not center vertically.

PARENT CONTAINER
CHILD DIV
/* Give the child a width, then auto margins share the free space. */
.child {
  width: 190px;
  margin: 0 auto;
}

Remember: margin: 0 auto means top/bottom margin is 0 and left/right margins are automatic.

02

Center both ways with Flexbox

Make the parent a flex container. These two rules center its child horizontally and vertically.

PARENT CONTAINER
CHILD DIV
Centered left-to-right and top-to-bottom
/* Put these rules on the PARENT, not the child. */
.parent {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center;     /* vertical */
}

Remember: The parent needs some height for vertical centering to be visible.

03

Center both ways with CSS Grid

A compact alternative: place-items: center centers the child on both axes.

PARENT CONTAINER
CHILD DIV
/* Put this on the PARENT. */
.parent {
  display: grid;
  place-items: center;
}

Remember: Like Flexbox, the parent needs height if you want to see vertical centering.

04

Center with absolute positioning

Place the child at the parent's midpoint, then shift it back by half its own size.

PARENT CONTAINER
CHILD DIV
/* Parent establishes the positioning area. */
.parent {
  position: relative;
}

/* These rules go on the CHILD. */
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Remember: The parent needs position: relative so the child is positioned inside it.