CSS
Perfectly Center Elements with CSS Flexbox & Grid
Discover how to perfectly center any element, both horizontally and vertically, using modern CSS Flexbox and Grid properties for robust and responsive layouts.
/* Flexbox Method */
.flex-centered-container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
min-height: 100vh; /* Example: full viewport height */
}
/* CSS Grid Method */
.grid-centered-container {
display: grid;
place-items: center; /* Shorthand for align-items and justify-items */
min-height: 100vh;
}
.item {
width: 100px;
height: 100px;
background-color: #007bff;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
}
How it works: This snippet demonstrates two highly effective methods for centering any element within its parent container. The Flexbox method uses `display: flex` on the parent, then `justify-content: center` for horizontal alignment and `align-items: center` for vertical alignment. The CSS Grid method offers an even more concise approach with `display: grid` on the parent, followed by `place-items: center`, which is a shorthand for both `align-items: center` and `justify-items: center`. Both techniques provide robust, responsive centering.