CSS
Flexbox: Perfectly Center Content Horizontally and Vertically
Learn to perfectly center any element both horizontally and vertically within its parent container using CSS Flexbox properties `display: flex`, `justify-content: center`, and `align-items: center`.
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Example: Take full viewport height */
border: 1px solid #ccc; /* For visualization */
}
.centered-item {
padding: 20px;
background-color: #f0f0f0;
border: 1px dashed #999;
text-align: center;
}
/* HTML Structure */
/*
<div class="container">
<div class="centered-item">
<h1>Hello, Centered World!</h1>
<p>This content is perfectly centered.</p>
</div>
</div>
*/
How it works: This snippet demonstrates the simplest and most robust way to center an item within its parent using Flexbox. By setting `display: flex` on the parent, its direct 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), achieving perfect centering.