CSS
Effortless Vertical and Horizontal Centering with Flexbox
Discover how to perfectly center any element both vertically and horizontally within its container using simple and powerful CSS Flexbox properties: `justify-content` and `align-items`.
.container {
display: flex;
justify-content: center; /* Horizontally centers content */
align-items: center; /* Vertically centers content */
height: 100vh; /* Example: container takes full viewport height */
border: 2px dashed #ccc;
}
.centered-item {
width: 200px;
height: 150px;
background-color: #007bff;
color: white;
display: flex; /* Optional: if the item itself needs centered content */
justify-content: center;
align-items: center;
font-size: 1.2em;
}
How it works: This code shows the most straightforward way to center an item within its parent using Flexbox. By setting `display: flex` on the container, `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). This combination provides perfect centering, making it a 'holy grail' solution for many layout needs.