Centering in CSS has historically been a challenge, but modern CSS has made it trivial. This post covers the two primary methods for perfect centering, both horizontally and vertically. Flexbox is great for single items or aligning items along one axis. CSS Grid offers powerful two-dimensional alignment. We show how display: grid and place-items: center can center an element with just two lines of code.
CSS: Modern Centering Techniques
/* Using Flexbox */
.flex-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Using Grid */
.grid-container {
display: grid;
place-items: center;
min-height: 100vh;
}
The place-items property is a game changer.