CSS
Center Element Horizontally and Vertically with Flexbox
Learn how to perfectly center any element within its parent container using modern CSS Flexbox properties for robust and responsive alignment.
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
min-height: 100vh; /* Example: make container full viewport height */
border: 1px solid #ccc; /* For visualization */
}
.centered-item {
width: 100px;
height: 100px;
background-color: #007bff;
color: white;
display: flex; /* Optional: to center text inside item */
justify-content: center;
align-items: center;
}
How it works: This snippet demonstrates how to achieve perfect horizontal and vertical centering using Flexbox. By setting `display: flex` on the parent 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). The `min-height: 100vh` ensures the container has enough space to demonstrate vertical centering.