Html CSS 如何拉伸以适应和保持纵横比?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7394884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:34:59  来源:igfitidea点击:

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

htmlimagecssaspect-ratio

提问by JZ.

I have the following css:

我有以下CSS:

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

That corresponds to this HTML:

这对应于这个 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:

如果我使用 css3 background-size: 175px 160px; 纵横比真的很乱,导致像这样一团糟:

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.

有没有办法拉伸图像以适应 div?但是以保持纵横比的方式?我想要一个自动裁剪。

回答by robertc

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

这应该可以工作(在支持 的浏览器中background-size):

background-size: 175px auto;

You could also try:

你也可以试试:

background-size: cover;

Or:

或者:

background-size: contain;

There's a good explanation on MDC.

MDC 上有很好的解释。

回答by Brian D

Does it need to be a background image?

它需要是背景图像吗?

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


<img src="your-photo.png">

回答by Harish_N

You can use the CSS Object-fitproperty.

您可以使用 CSS Object-fit属性。

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

Object-fit can have the following values.

Object-fit 可以具有以下值。

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

包含、覆盖、填充、无、缩小。请参阅上面的链接了解更多信息。

回答by Gus Rodriguez

You can use the background-sizeproperty with the containvalue:

您可以使用background-size具有以下contain值的属性:

background-size: contain;

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

这是一个工作示例: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.

在上面的例子中,身体在背景中有一个拉伸的图像。还有两个具有任意大小的 div,以及另一个适合并保持纵横比的图像。

回答by Dirigible

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

我找到了这个方法,如果使用 img 不是背景:

        min-width: 100%;
        max-width: 100%;
        min-height: 100%;
        max-height: 100%;
        object-fit: contain;