CSS
Center an Element Vertically and Horizontally with Flexbox
Discover how to perfectly center any element both vertically and horizontally within its parent container using modern CSS Flexbox properties for responsive designs.
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
height: 100vh; /* Example: make container full height */
border: 1px solid #ccc;
}
.centered-item {
padding: 20px;
background-color: #f0f0f0;
border: 1px dashed #999;
}
How it works: This snippet demonstrates the simplest and most robust way to center an item 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). A defined height on the container is often necessary for vertical centering to have an effect.