CSS
Perfectly Center Any Element Vertically and Horizontally with Flexbox
Discover the simplest and most robust way to perfectly center any element both vertically and horizontally within its parent container using CSS Flexbox properties like `justify-content` and `align-items`.
.parent-container {
display: flex;
justify-content: center; /* Centers horizontally along the main axis */
align-items: center; /* Centers vertically along the cross axis */
height: 100vh; /* Example: Takes full viewport height */
border: 1px solid #ccc;
}
.centered-item {
width: 200px;
height: 100px;
background-color: #007bff;
color: white;
display: flex; /* Can center its own content too if needed */
justify-content: center;
align-items: center;
}
How it works: This code snippet provides the definitive solution for perfectly centering any item within its parent container using Flexbox. By setting `display: flex` on the parent, `justify-content: center` aligns items along the main axis (horizontally by default), and `align-items: center` aligns them along the cross axis (vertically by default).