htmlcssimageobject-fit

How can I use "object-fit: contain" in CSS and still have a border radius on the image?


I'm trying to show an image in a "lightbox" style so that it will fill the available area on screen, in this case 90% of the width of the page and 70% of the height.

Using object-fit: contain; seems to be the de facto way to do that but it's not quite working with border-radius. Is it possible to use object-fit on an <img> and still have the border radius applied as intended?

You'll need to resize your browser window to see what happens when you run the below snippet. I've got the same code running in JSFiddle, as per the below video.

JSFiddle Video Demo

div {
  margin: auto;
  width: 90vw;
  height: 70vh;

  background-color: DeepSkyBlue;
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;

  border-radius: 50px;
  background-color: Crimson;
}
<div>
  <img src="https://images.freeimages.com/images/large-previews/773/koldalen-4-1384902.jpg">
</div>


Solution

  • Setting max-width and max-height seems to be what you need or expect:

    div {
      margin: auto;
      width: 90vw;
      height: 70vh;
      display:grid;
    
      background-color: DeepSkyBlue;
    }
    
    img {
      max-width: 100%;
      max-height: 100%; 
      margin:auto;/* x,y center if inside a grid or flex box */
     
      object-fit: contain;/* useless by now, img should keep its ratio */
      border-radius: 50px;
      border-radius: calc( 5vw + 5vh); /* will scale, maybe you find this usefull */
      background-color: Crimson;
    }
    <div>
      <img src="https://images.freeimages.com/images/large-previews/773/koldalen-4-1384902.jpg">
    </div>