CSS
Perfect Centering with CSS Flexbox and Grid
Master perfect element centering in CSS using modern Flexbox and Grid techniques. Learn to vertically and horizontally align any content effortlessly within its parent.
/* Using Flexbox */
.flex-container {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
height: 100vh; /* Example: full viewport height */
border: 1px solid #ccc;
}
/* Using Grid */
.grid-container {
display: grid;
place-items: center; /* Shorthand for justify-items & align-items */
height: 100vh; /* Example: full viewport height */
border: 1px solid #ccc;
}
.centered-item {
padding: 20px;
background-color: lightblue;
}
How it works: This snippet demonstrates two common ways to perfectly center an element within its parent using modern CSS. With Flexbox, `display: flex` combined with `justify-content: center` (horizontal) and `align-items: center` (vertical) achieves the centering. For CSS Grid, the `place-items: center` shorthand property performs both horizontal and vertical alignment simultaneously, offering a concise and powerful solution for any content.