Mahdi Ghiasi Mahdi Ghiasi - 11 months ago 111
CSS Question

CSS Image size, how to fill, not stretch?

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:


Stretched Image:


Filled Image:


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

Answer Source

If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property.

<div class="container"></div>​

.container {
    width: 150px;
    height: 100px;
    background-image: url("");
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 50% 50%;

While cover will give you a scaled up image, contain will give you a scaled down image. Both will preserve the pixel aspect ratio. (using cover) (using contain)

This approach has the advantage of being friendly to Retina displays as per Thomas Fuchs' quick guide.

It's worth mentioning that browser support for both attributes excludes IE6-8.