Skip to content
CSS

Center a Div with Flexbox and Grid

Center elements horizontally and vertically using Flexbox, Grid, and absolute positioning.

By EZ4Code Team
centerlayoutbeginner

Code

/* Center with Flexbox (most common) */
.center-flex {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

/* Center with Grid */
.center-grid {
  display: grid;
  place-items: center;
}

/* Center absolutely positioned element */
.center-abs {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* Center text horizontally */
.center-text {
  text-align: center;
}

Explanation

Shows four centering techniques: Flexbox (align-items + justify-content), Grid (place-items), absolute positioning with transform, and text-align for inline content. Flexbox and Grid are the modern preferred approaches for both horizontal and vertical centering. Absolute positioning with translate is useful for overlaying elements.

More CSS Snippets