CSS how do you stretch to fit and maintain the aspect ratio?

JZ. picture JZ. · Sep 13, 2011 · Viewed 27.9k times · Source

I have the following css:

.mod.left {
background-image: url("http://www.myimage.jpg");
display: block;
height: 160px;
overflow: hidden;
width: 175px;
}

That corresponds to this HTML:

<div class="mod left"></div>

It results in this mess:

enter image description here

if I use the css3 background-size: 175px 160px; The aspect ratio is really messed up resulting in a mess like this:

enter image description here

Is there a way to stretch an image to fit a div? But in a way in which the aspect ratio is maintained? I want an auto crop.

Answer

robertc picture robertc · Sep 13, 2011

This should work (in browsers which support background-size):

background-size: 175px auto;

You could also try:

background-size: cover;

Or:

background-size: contain;

There's a good explanation on MDC.