Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 748
JZ. Avatar asked Sep 12 '11 22:09

JZ.


People also ask

How do you maintain aspect ratio in CSS?

In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I keep an image aspect ratio in CSS?

The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.

How do I stretch a fit image in CSS?

You can use the CSS background-size: cover; to stretch and scale an image in the background with CSS only. This scales the image as large as possible in such a way that the background area is completely covered by the background image, while preserving its intrinsic aspect ratio.


2 Answers

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.

like image 163
robertc Avatar answered Nov 15 '22 14:11

robertc


Does it need to be a background image?

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


<img src="your-photo.png">
like image 20
Brian D Avatar answered Nov 15 '22 14:11

Brian D