Loading lessons...
Centering Images
Centering Images
Three reliable ways to center an image: block, flexbox, and grid.
1. Make it a block + auto margins
img {
display: block;
margin: 0 auto;
}
Works because auto margins split the leftover space evenly. (Text-align on parents only affects inline images.)
2. Flexbox
.container {
display: flex;
justify-content: center;
}
Also center vertically with align-items: center.
3. Grid
.container {
display: grid;
place-items: center; /* both axes at once */
}
A centered circle avatar
.avatar {
width: 80px;
height: 80px;
border-radius: 50%;
object-fit: cover; /* crop nicely */
display: block;
margin: 0 auto;
}
TL;DR
display: block; margin: 0 auto= classic horizontal center.- Grid
place-items: center= center on BOTH axes. - For avatars
border-radius: 50%+object-fit: cover. - For text-align: it only hands inline content, not block images.