CSS
CSS Flexbox: Perfectly Center Content Horizontally and Vertically
Learn to perfectly center any content within a container using CSS Flexbox. This snippet demonstrates robust horizontal and vertical alignment for responsive designs.
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Example: Full viewport height */
border: 1px solid #ccc;
}
.item {
padding: 20px;
background-color: lightblue;
color: #333;
}
How it works: This snippet shows how to achieve perfect centering of an item inside a container using Flexbox. By setting 'display: flex' on the parent, 'justify-content: center' aligns children along the main axis (horizontally by default), and 'align-items: center' aligns them along the cross axis (vertically by default). This combination ensures the item is centered in both dimensions.