CSS
Center Content Horizontally and Vertically with Flexbox
Master centering elements in CSS using Flexbox. This snippet demonstrates how to perfectly align any element both horizontally and vertically within its parent container with just a few lines of CSS.
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Example: full viewport height */
border: 1px solid #ccc;
}
.item {
padding: 20px;
background-color: lightblue;
}
/* HTML Context */
/*
<div class="container">
<div class="item">I'm centered!</div>
</div>
*/
How it works: This technique uses `display: flex` on the parent container. `justify-content: center` aligns children along the main axis (horizontally by default), and `align-items: center` aligns them along the cross axis (vertically by default), achieving perfect centering within the container.