Html 自动调整图像大小以适应比例但不拉伸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30670218/
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 11:35:55  来源:igfitidea点击:

Auto resize image to fit proportions but don't stretch

htmlcss

提问by ThanosFisherman

I want to resize an image based on screen size but I don't want that image to exceed its actuall pixels when screen is too big. So far I managed to do this

我想根据屏幕大小调整图像大小,但当屏幕太大时,我不希望该图像超过其实际像素。到目前为止,我设法做到了这一点

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;">
<img src="myImg.png" style="width: 80%">
</div>

This maintains the proportions I want but when Screen is too big it also stretches the image. I don't want that.

这保持了我想要的比例,但是当屏幕太大时它也会拉伸图像。我不想要那个。

回答by ns1234

The css for a responsive image is as follows:

响应式图片的 css 如下:

    max-width: 100%;
    height: auto;

This will make the image scale down with the size of its container, without exceeding the image's natural width. However, using width: 100%;will force the image to be as wide as its container, regardless of the image's actual size.

这将使图像随着其容器的大小而缩小,而不会超过图像的自然宽度。但是,使用width: 100%;将强制图像与其容器一样宽,而不管图像的实际大小。

A few other notes:

其他一些注意事项:

  • align="center"is deprecated. You should use css to align content, so text-align: center;.
  • Using position: static;is unnecessary, as it is the default value for the position property. The only time I can think of where you'd need to use this is if you need to override some other css.
  • Unless you are absolute positioning your div (which you are not), then top: 0; left: 0;will do nothing.
  • align="center"已弃用。您应该使用 css 来对齐内容,因此text-align: center;.
  • Usingposition: static;是不必要的,因为它是 position 属性的默认值。我能想到的唯一一次你需要使用它的地方是你是否需要覆盖其他一些 css。
  • 除非你绝对定位你的 div(你不是),top: 0; left: 0;否则什么都不做。

Without seeing the rest of your code, I think this would be the best solution for what you are trying to accomplish:

在没有看到其余代码的情况下,我认为这将是您尝试完成的最佳解决方案:

    <div style="text-align: center;">
       <img src="myImg.png" style="max-width: 100%; height: auto;" alt="FYI, image alt text is required" />
    </div>

回答by Laura Vaca

If you also set a max-widthattribute, it will limit how large the image can get. like so:

如果您还设置了一个max-width属性,它将限制图像的大小。像这样:

<div align="center" style="position:static; height: 100%; width: 100%; top:0;left 0;">
    <img src="myImg.png" style="width: 80%; max-width: 300px;">
</div>

You can make this max-widthany size you want, as long as it doesn't exceed the actual width of the image. Also possible with height.

max-width只要不超过图像的实际宽度,您可以将其设为任何您想要的大小。也可能与高度。

回答by mumukulux

class="img-thumbnail" 

could be the solution.

可能是解决方案。