CSS
Center Element Vertically and Horizontally with Flexbox or Grid
Learn how to perfectly center any element both vertically and horizontally within its parent container using modern CSS Flexbox or Grid properties.
/* Flexbox Centering */
.flex-container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
height: 100vh; /* Example: Full viewport height */
border: 2px dashed #ccc;
}
.flex-item {
padding: 20px;
background-color: lightblue;
}
/* Grid Centering */
.grid-container {
display: grid;
place-items: center; /* Centers both horizontally and vertically */
height: 100vh; /* Example: Full viewport height */
border: 2px dashed #ccc;
}
.grid-item {
padding: 20px;
background-color: lightcoral;
}
How it works: This snippet demonstrates two powerful methods for perfectly centering an item. Flexbox uses `justify-content: center` for horizontal alignment and `align-items: center` for vertical alignment on the container. CSS Grid offers a more concise solution with `place-items: center` on the container, which is a shorthand for `align-items: center` and `justify-items: center`.