CSS
Center Content Both Horizontally and Vertically with Flexbox
Master vertical and horizontal centering of any element within its container using a simple yet powerful CSS Flexbox pattern, including consistent spacing with the `gap` property.
.center-container {
display: flex;
justify-content: center; /* Horizontally center content */
align-items: center; /* Vertically center content */
height: 300px; /* Example height for the container */
width: 100%;
border: 2px dashed #999;
background-color: #f9f9f9;
flex-wrap: wrap; /* Allow items to wrap if needed */
gap: 15px; /* Spacing between centered items */
}
.centered-item {
background-color: #007bff;
color: white;
padding: 20px 30px;
font-size: 1.2em;
border-radius: 5px;
}
How it works: This snippet shows the most straightforward way to center content both horizontally and vertically using Flexbox. By setting `display: flex` on the parent container, `justify-content: center` centers items along the main axis (horizontally by default for `flex-direction: row`), and `align-items: center` centers them along the cross axis (vertically by default). `flex-wrap: wrap` allows multiple items to wrap and still be centered, and `gap` provides consistent spacing between them.