htmlcssobject-fit

Object-fit doesn't work with fixed width and height


.block {
  width: 500px;
  height: 300px;
}

img {
  max-width: 100%;
  object-fit: contain;
}
<div class="block">
  <img src="http://dialog.localhost/upload/postomat/04a/04aeacfed49dd7eda5f469f57b822f7f.jpg" alt="">
</div>

In my opinion, the picture should shrink to fit into the block, but this does not happen. Why?


Solution

  • specify your image to the block

    specify both height and width:

    width: 100%;
    height: 100%;
    

    use object-fit: cover or object-fit: fill

    .block {
      width: 500px;
      height: 300px;
      border: 1px solid black;
    }
    
    .block img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    <div class="block">
      <img src="https://material.angular.io/assets/img/examples/shiba2.jpg" alt="">
    </div>