I want to show an image with rounded corners. So the image must stretch to the container but doesn't crop any part, like object-fit: contain
. However, border-radius
applies to image element, not the picture content. Here is an example (also JSFiddle):
body {
width: 100vw;
height: 100vh;
margin: 0;
}
div {
width: 100%;
height: 100%;
}
img {
width: 100%;
height: 100%;
object-fit: contain;
border-radius: 20%;
}
<div>
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg">
</div>
You can check how it works when you resize the viewport.
So, is there a way to make the image element resize it's borders in both directions to adjust to the container, just like object-fit
does?
Or maybe a way to apply a "crop-by-rounded-rect filter" on the image content?
I've also had this problem and I've found a way to do it. If you set the height and width to auto the img element maintains its aspect ratio and the image touches the borders. You can then use max-width and max-height instead of width and height.
img {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
object-fit: contain;
border-radius: 20%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
You may also have to center the img on the parent div as now if it's smaller than the maximum size it will move to the top left.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With