How do I center a div in CSS?

Short answer

Use display: grid; place-items: center on the parent. For flexbox, display: flex; align-items: center; justify-content: center.

css
.parent {
  display: grid;
  place-items: center;
  min-height: 100vh;      /* it needs height to center within */
}

place-items is shorthand for align-items and justify-items together. Two words, both axes.

#The flexbox version

css
.parent {
  display: flex;
  align-items: center;      /* cross axis — vertical by default */
  justify-content: center;  /* main axis — horizontal by default */
}

Remember: with flex-direction: row, justify-content is horizontal. Change the direction and the two swap meaning. That is the single most confusing thing about flexbox.

#Horizontal only, in normal flow

css
.box {
  max-width: 40rem;
  margin-inline: auto;
}

margin-inline: auto is the modern spelling of margin: 0 auto, and it respects writing direction.

#Absolute positioning, when you need it

css
.overlay {
  position: absolute;
  inset: 0;
  margin: auto;
  width: fit-content;
  height: fit-content;
}

inset: 0 plus margin: auto centers in both directions without the old transform: translate(-50%, -50%) trick — and without the blurry text that half-pixel transforms cause.