CSS
Center Anything with CSS Flexbox
Learn to perfectly center any element both horizontally and vertically within its parent container using modern CSS Flexbox properties for clean layouts.
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
min-height: 100vh; /* Example: make container full viewport height */
border: 1px solid #ccc;
}
.centered-item {
padding: 20px;
background-color: lightblue;
}
How it works: This snippet demonstrates how to perfectly center a single child element within its parent using Flexbox. By setting `display: flex` on the parent, `justify-content: center` centers items along the main axis (horizontally by default), and `align-items: center` centers them along the cross axis (vertically by default).