CSS
Center Any Content Horizontally and Vertically with Flexbox
Achieve perfect horizontal and vertical centering for any element or group of elements using simple Flexbox properties, ideal for modals, loaders, or single-item layouts.
/* HTML */
<div class="container">
<div class="centered-item">Hello, Centered World!</div>
</div>
/* CSS */
.container {
display: flex;
justify-content: center; /* Centers content horizontally */
align-items: center; /* Centers content vertically */
min-height: 100vh; /* Example: take full viewport height */
border: 2px dashed #ccc; /* For visualization */
}
.centered-item {
padding: 20px;
background-color: #f0f8ff;
border: 1px solid #add8e6;
}
How it works: This snippet demonstrates the most straightforward way to center any content, both horizontally and vertically, within a parent container using Flexbox. By setting `display: flex` on the parent, we enable Flexbox context. Then, `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). `min-height: 100vh` is added to the container as an example to ensure it takes up enough space to visibly demonstrate vertical centering across the viewport.