CSS
Universal Centering with Flexbox or Grid
Learn the most common and robust CSS techniques to perfectly center any element, both horizontally and vertically, using Flexbox or Grid.
/* Flexbox Centering */
.flex-container {
display: flex;
justify-content: center; /* Horizontally center children */
align-items: center; /* Vertically center children */
min-height: 200px; /* Example height */
border: 1px dashed #ccc;
}
.flex-item {
padding: 20px;
background-color: lightblue;
}
/* Grid Centering */
.grid-container {
display: grid;
place-items: center; /* Shorthand for justify-items & align-items */
min-height: 200px; /* Example height */
border: 1px dashed #ccc;
}
.grid-item {
padding: 20px;
background-color: lightcoral;
}
/* Centering a single item within its own Flex/Grid container */
.self-centered {
display: flex; /* or display: grid; */
min-height: 200px;
border: 1px dashed #ccc;
}
.self-centered > div {
margin: auto; /* Works for both flex and grid children */
padding: 20px;
background-color: lightgreen;
}
How it works: This snippet demonstrates three common centering methods. For a Flexbox container, `justify-content: center` (horizontal) and `align-items: center` (vertical) will center all direct children. For a Grid container, `place-items: center` is a convenient shorthand for `justify-items` and `align-items`. Additionally, setting `margin: auto` on a direct child of a Flex or Grid container will perfectly center that single item within the available space.