I want to contain an image fully within a div
, and I am proceeding as stated here, which works exactly as I want. Additionally, I want to add a border radius to the image corners, so I am using the property border-radius
. However, after configuring the image within the div
it stopped working. This is my HTML code:
<div style="width: 50%; height: 77vh; background-color: red;">
<img src="https://d3h1lg3ksw6i6b.cloudfront.net/media/image/2021/07/08/490b92922df3407cb5b91d3122a43579_Pavillon-Ledoyen.jpg" style="width: 100%; height: 100%; object-fit: contain; overflow: hidden; border-radius: 11px;">
</div>
How can I have the two functionalities combined?
3
Answers
Border doesn’t apply due to the object-fit property. Remove it, and everything will be fine. To align the image, you can set the container to flex and adjust the image alignment as required.
But, the behavior of the image is now not configured, but you can build on this and think further.
P.S If you need object-fit: contain , then you can set for img width: auto; The behavior will be similar.
Unfortunately, it’s not really possible. When you use
object-fit: contain
, the image properly scales itself so that it can be fully seen within its container, but withwidth: 100%
andheight: 100%
, it’s still as if the bounderies of the<img>
match the boundaries of its container (imagine that the remainder of the<img>
space is taken up by an invisible fill, if that makes sense). In other words, if you examine the<img>
in the devtools, you’ll see that it still fills the entire container even though the colored part is constrained.That’s why
border-radius
doesn’t really work as expected withobject-fit: contain
. It is working, but it acts on the entire width/height of the<img>
that you see in devtools—it doesn’t’ know how to just act on the actual colored image part. If you take that CodePen and change the<div>
aspect ratio so that it’s only slightly wider than the image and then change theborder-radius
on the image to something large like 10000px, you’ll better see what I mean: https://codepen.io/SonicBoomNFA/pen/vYbOqYR.To contain an image fully within a div and add rounded corners (border-radius), you can wrap the image in an additional div and apply the border-radius to that div.