CSS

Achieve Perfect Vertical and Horizontal Centering with Flexbox and Grid

Learn how to flawlessly center any element both vertically and horizontally using concise CSS Flexbox and Grid properties, perfect for modals or hero sections.

/* Flexbox Centering */
.flex-container {
  display: flex;
  justify-content: center; /* Horizontally center */
  align-items: center;     /* Vertically center */
  height: 200px;           /* Or min-height: 100vh; for full viewport */
  border: 1px solid #ccc;
}

/* Grid Centering */
.grid-container {
  display: grid;
  place-items: center;   /* Shorthand for align-items and justify-items */
  height: 200px;         /* Or min-height: 100vh; for full viewport */
  border: 1px solid #ccc;
}

.centered-item {
  padding: 20px;
  background-color: #f0f0f0;
}
How it works: This snippet demonstrates two highly effective methods for perfectly centering an item within its container. Flexbox uses `justify-content: center` for horizontal alignment and `align-items: center` for vertical alignment on the parent. CSS Grid simplifies this even further with the `place-items: center` shorthand property applied to the grid container, making it incredibly concise for positioning content.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs