CSS
CSS Flexbox for Perfect Vertical and Horizontal Centering
Learn to perfectly center any element both vertically and horizontally within its parent container using simple CSS Flexbox properties for elegant layouts.
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
height: 100vh; /* Example: take full viewport height */
border: 1px solid #ccc;
}
.centered-item {
padding: 20px;
background-color: lightblue;
border-radius: 5px;
text-align: center;
}
How it works: This snippet demonstrates how to use Flexbox to center an item both vertically and horizontally within its parent. By setting `display: flex` on the container, its children become flex items. `justify-content: center` aligns items along the main axis (horizontally by default), while `align-items: center` aligns them along the cross axis (vertically by default), achieving perfect centering.