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:
if I use the css3 background-size: 175px 160px; The aspect ratio is really messed up resulting in a mess like this:
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.
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.
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.
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.
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.
Does it need to be a background image?
img{
width:300px;
height:auto;
}
<img src="your-photo.png">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With