Need a perfectly round image without cropping or wrapping it in extra elements? Here are four lines of CSS that will save the day.
We
all know that setting border-radius: 50%
on an image is an easy way to make it round,
but that doesn't work so well if the image isn't perfectly square. Let's take a look at
three different images from placekitten, one square, one
portrait, and one landscape.
Since we want these to be perfectly round, like an avatar, we'll need to set the dimensions and add
the usual border-radius trick. Let's use the rounded
class to keep things simple.
<img src="https://placekitten.com/200/200" class="rounded">
<img src="https://placekitten.com/200/400" class="rounded">
<img src="https://placekitten.com/400/200" class="rounded">
img.rounded {
height: 100px;
width: 100px;
border-radius: 50%;
}
Here's what we end up with. Notice how the portrait and landscape images are squished?
In the good ol' days of CSS, we'd need to crop the images manually or add a wrapper with some
overflow: hidden
magic to fix this. Fortunately, we have object-fit
now!
img.rounded {
height: 100px;
width: 100px;
border-radius: 50%;
object-fit: cover;
}
Perfect! With just four lines of CSS, we've managed to get rounded images that aren't squished. You're probably wondering what the catch is — there are two.
First, you don't have control over how the images are positioned. You're pretty much stuck with them being centered. Second, this property doesn't work in Internet Explorer. Of course, if you're targeting modern browsers, you're good to go!
Never used object-fit
before?
Learn more about it here.