开发者

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:

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

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

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

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.


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">


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.


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜