【问题标题】:Is there a way to specify either max height or max width for an image?有没有办法指定图像的最大高度或最大宽度?
【发布时间】:2019-05-30 23:19:16
【问题描述】:

无论如何要保持最大宽度或最大高度的以下纵横比,以下是我面临的情况。 最大宽度或高度应为 500px

400x300 image - no resizing (both sides below 500 maximum size)
500x500 image - no resizing (both sides at exactly 500 maximum size).
600x400 image - resize to 500x333 (preserves same ratio) as one side is over 500 pixels.
1000x1200 image -resize to 417x500 (preserves same ratio), as both sides are over 500 pixels

【问题讨论】:

  • CSS max-height: 500px; max-width: 500px;?或者你追求更复杂的东西? (在这种情况下,您可能需要扩展您的问题)
  • 这个 1000x1200 图像怎么样 - 调整为 417x500(保持相同的比例),根据最大高度:500 像素和最大宽度:500 像素,对于分辨率为 1000*1200 的图像将具有 500*500 ,我不想要这个,我也想保持纵横比,在这种情况下高度为500px,宽度将被计算。
  • 如果你设置他们的widthheight会发生这种情况,但是使用max-widthmax-height可以保持纵横比。我添加了一个答案来演示。
  • 再想一想,如果您没有在任何地方使用原始较大的尺寸(以防图像大于 500 像素),您应该调整图像的大小以更快地处理和加载并使用更少的空间。
  • 是的,调整大小很好,感谢@EdsonHoracioJunior的建议

标签: html css responsive-design responsive-images


【解决方案1】:

将 CSS 属性 max-widthmax-height 设置为限制值,同时将图像保留为 auto,因为它是 widthheight 可用于保持纵横比,同时限制最大尺寸,如下所示:

img {
  display: block;
  width: auto;
  height: auto;
  max-width: 500px;
  max-height: 500px;
}
<img src="https://via.placeholder.com/50x50" />
<img src="https://via.placeholder.com/500x100" />
<img src="https://via.placeholder.com/100x500" />
<img src="https://via.placeholder.com/1000x200" />
<img src="https://via.placeholder.com/200x1000" />

大于 500 像素的图片将调整大小以适应限制,而较小的图片将保留其原始大小。

【讨论】:

  • 感谢您的回答,我只是在测试。
猜你喜欢
  • 2011-04-10
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
相关资源
最近更新 更多