CSS
Flexbox: Perfect Centering (Horizontal & Vertical)
Achieve perfect horizontal and vertical centering of any element inside its parent using CSS Flexbox. This widely used technique is simple, efficient, and perfect for UI components like modals or alerts.
.container {
display: flex;
justify-content: center; /* Horizontally centers content */
align-items: center; /* Vertically centers content */
height: 100vh; /* Example: Takes full viewport height */
border: 1px solid #ccc;
}
.item {
width: 200px;
height: 150px;
background-color: #007bff;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5em;
}
How it works: This snippet demonstrates the simplest and most robust way to perfectly center an item both horizontally and vertically within its parent using Flexbox. By setting `display: flex` on the parent, its children become flex items. `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). This combination ensures the child element is precisely centered.