Flexbox Centering Patterns

Center elements horizontally and vertically using flexbox with justify-content and align-items properties.

CssConfig Management

Code

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

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

Flexbox Centering Patterns

Center elements horizontally and vertically using flexbox with justify-content and align-items properties.

Code

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

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

Explanation

justify-content and align-items centre a flex item on both axes, replacing margin-auto hacks. Expected behavior: with a fixed-height container the child sits centred vertically and horizontally. Caveat: with the default align-items: stretch a child of height auto fills the container, so centring needs a definite main size or align-items: center.

Interactive Tools for This Topic