Lesson 27 / 28

Centering Techniques

Three reliable ways to center content, for every situation.

Flexbox centering

Works for any number of children, any size.

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

Grid centering

place-items: center is a one-line shortcut for justify + align on a grid.

.center-grid {
  display: grid;
  place-items: center;
  min-height: 100vh;
}

Absolute + transform

For a single element inside a positioned parent: position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); — works even when the element's size is unknown.

Quick check: Which is the shortest way to center children in a grid container?

  • place-items: center
  • margin: auto auto
  • text-align: center
Answer

place-items: center — place-items: center centers grid children on both axes in one declaration.