有没有办法指定图像的最大高度或最大宽度?

时间:2019-01-04 11:24:48

标签: html css css3 responsive-design responsive-images

无论如何,要保持以下纵横比的最大宽度或最大高度,以下是我所面临的情况。 最大宽度或高度应为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

1 个答案:

答案 0 :(得分:1)

将CSS属性max-widthmax-height设置为限制值,同时将图像的autowidth保留为height像这样限制最大尺寸的长宽比:

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像素的图像将调整大小以适应限制,而较小的图像将保留其原始尺寸。