CSS – How to Fill Image Size Without Stretching

cssimage

I have an image, and I want to set it a specific width and height (in pixels)

But If I set width and height using css (width:150px; height:100px), image will be stretched, and It may be ugly.

How to Fill images to a specific size using CSS, and not stretching it?

Example of fill and stretching image:

Original Image:

Original

Stretched Image:

Stretched

Filled Image:

Filled

Please note that in the Filled image example above: first, image is resized to 150×255 (maintained aspect ratio), and then, it cropped to 150×100.

Best Answer

You can use the css property object-fit. ("sets how the content of a replaced element, such as an <img> or <video>, should be resized to fit its container.")

.cover {
  object-fit: cover;
  width: 50px;
  height: 100px;
}
<img src="https://i.sstatic.net/2OrtT.jpg" class="cover" width="242" height="363" />

See example here

There's a polyfill for IE: https://github.com/anselmh/object-fit

Related: object-position (specifies the alignment of an element's contents within its box.)

Related Question