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

5

18

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.

Sweetandsour answered 12/9, 2011 at 22:43 Comment(1)
your example is working on firefox 6.0.2. the image is cropped with correct ratio. peaceQuintessence
B
36

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.

Bartie answered 12/9, 2011 at 22:59 Comment(0)
C
5

Does it need to be a background image?

img{
width:300px;
height:auto;
}


<img src="your-photo.png">
Celsacelsius answered 12/9, 2011 at 22:53 Comment(0)
C
3

You can use the background-size property with the contain value:

background-size: contain;

Here is a working example: https://jsfiddle.net/gusrodriguez/auuk97hf/1/

In the example above, the body has an stretched image in the background. Also there are two divs with arbitrary size, and with another image that fits and keep the aspect ratio.

Catalyst answered 2/12, 2016 at 13:50 Comment(0)
K
2

You can use the CSS Object-fit property.

{
 height: 160px;
 width: 175px;
 object-fit: cover;
}

Object-fit can have the following values.

contain, cover, fill, none, scale-down. Please refer to above link for more info.

Kennedy answered 31/3, 2018 at 3:28 Comment(0)
V
1

I found this method, if using an img not a background:

        min-width: 100%;
        max-width: 100%;
        min-height: 100%;
        max-height: 100%;
        object-fit: contain;
Vogeley answered 26/4, 2020 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.