CSS
Effortless Centering with CSS Flexbox
Achieve perfect horizontal and vertical centering for any element using a minimal amount of CSS Flexbox properties on the parent container, ideal for layouts and components.
.container {
display: flex;
justify-content: center; /* Horizontally center content */
align-items: center; /* Vertically center content */
min-height: 100vh; /* Example: occupy full viewport height */
border: 1px dashed #ccc;
}
.item {
width: 150px;
height: 150px;
background-color: #007bff;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
}
How it works: This snippet demonstrates how to perfectly center a child element within its flex container. By applying `display: flex;` to the parent, `justify-content: center;` horizontally aligns the content, and `align-items: center;` handles vertical alignment. Setting `min-height: 100vh;` on the container ensures vertical centering is visible across the entire viewport.