CSS
Center Content with Flexbox (Horizontally & Vertically)
Master centering elements precisely in a container using CSS Flexbox. This snippet demonstrates robust horizontal and vertical alignment for any content.
.container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
min-height: 100vh; /* Example for full viewport height */
border: 1px solid #ccc;
}
.item {
padding: 20px;
background-color: lightblue;
border-radius: 8px;
font-family: sans-serif;
}
How it works: This CSS snippet utilizes Flexbox to perfectly center an item (or a group of items) both horizontally and vertically within its parent container. `display: flex;` initializes the flex context. `justify-content: center;` aligns items along the main axis (horizontal by default), and `align-items: center;` aligns them along the cross axis (vertical by default). `min-height: 100vh;` is used as an example to give the container sufficient height for vertical centering to be visible, making it ideal for hero sections or modals.