Force an image to fit and keep aspect ratio

You can try CSS3 object-fit, and see browser support tables.

CSS3 object-fit/object-position Method of specifying how an object (image or video) should fit inside
its box. object-fit options include “contain” (fit according to aspect
ratio), “fill” (stretches object to fill) and “cover” (overflows box
but maintains ratio), where object-position allows the object to be
repositioned like background-image does.

JSFIDDLE DEMO

.container {
  width: 200px; /*any size*/
  height: 200px; /*any size*/
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container">
  <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg">
</div>

Related Info:

Leave a Comment