CSS
Perfectly Center Elements with CSS Flexbox
Learn to perfectly center any element horizontally and vertically within its parent using a minimal and highly effective CSS Flexbox solution.
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
height: 100vh; /* Example: take full viewport height */
border: 1px solid #ccc;
}
.centered-item {
padding: 20px;
background-color: #f0f0f0;
border: 1px dashed #999;
}
How it works: This snippet demonstrates the simplest way to center an item within a container using Flexbox. By setting `display: flex` on the parent, then `justify-content: center` for horizontal alignment and `align-items: center` for vertical alignment, the child element is perfectly centered. The `height` property on the container ensures it has enough space to center within, though this can be any defined height.