CSS/HTML
Perfect Centering with CSS Flexbox
Learn to perfectly center any element both horizontally and vertically using simple CSS Flexbox properties for clean and responsive layouts.
<div class="container">
<div class="centered-item">
Hello Centered!
</div>
</div>
<style>
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
height: 100vh; /* Or any fixed height */
width: 100%;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
.centered-item {
padding: 20px;
background-color: #f0f0f0;
border: 1px solid #aaa;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
How it works: This snippet demonstrates the simplest and most robust way to center an item within its parent container using Flexbox. By setting `display: flex` on the parent, `justify-content: center` handles horizontal alignment, and `align-items: center` handles vertical alignment. Setting a defined height on the parent (e.g., `height: 100vh`) is crucial for vertical centering to be visible when the content itself might be short.