CSS
Perfect Centering with Flexbox (Horizontal & Vertical)
Discover the easiest way to perfectly center any element horizontally and vertically within its parent container using just two simple CSS Flexbox properties.
.container {
display: flex;
justify-content: center; /* Horizontally centers content */
align-items: center; /* Vertically centers content */
width: 300px; /* Example width */
height: 200px; /* Example height */
background-color: #f0f0f0;
border: 1px solid #ccc;
}
.item {
width: 100px;
height: 100px;
background-color: #007bff;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
}
/* Basic HTML Structure for context:
<div class="container">
<div class="item">Centered!</div>
</div>
*/
How it works: This is one of the most common and powerful uses of Flexbox: perfectly centering an item within its parent. By setting `display: flex` on the parent container, and then applying `justify-content: center` (for horizontal alignment) and `align-items: center` (for vertical alignment), any direct child items will be precisely centered. This method is incredibly versatile and works regardless of the item's size or content, making it a go-to solution for centering in modern web development.