CSS
Perfectly Center an Element Vertically and Horizontally
Achieve perfect vertical and horizontal centering of any HTML element within its parent using minimal CSS Flexbox for clean, responsive layouts.
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
min-height: 100vh; /* Example: full viewport height */
border: 1px solid #ddd;
}
.centered-item {
width: 200px;
height: 100px;
background-color: #007bff;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.5em;
}
How it works: This snippet demonstrates the easiest way to perfectly center an item within its parent using CSS Flexbox.
By setting `display: flex` on the parent container, you enable Flexbox layout. Then, `justify-content: center` centers child items along the main axis (horizontally by default), and `align-items: center` centers them along the cross axis (vertically by default).
The `min-height: 100vh` on the container is just an example to ensure the container has enough vertical space to demonstrate vertical centering.