如何使用 HTML IMG 标签保持纵横比

新手上路,请多包涵

我正在使用 HTML 的 img 标签在我们的应用程序中显示照片。我已将其高度和宽度属性都设置为 64。我需要将任何图像分辨率(例如 256x256、1024x768、500x400、205x246 等)显示为 64x64。但是通过将 img 标签的高度和宽度属性设置为 64,它不会保持纵横比,所以图像看起来扭曲了。

供您参考,我的确切代码是:

 <img src="Runtime Path to photo" border="1" height="64" width="64">

原文由 sunil kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 975
1 个回答

不要设置高度和宽度。使用其中之一,将保持正确的纵横比。

 .widthSet {
    max-width: 64px;
}

.heightSet {
    max-height: 64px;
}
 <img src="https://placeimg.com/200/500/any/grayscale" />

<img src="https://placeimg.com/200/500/any/grayscale" width="64" />

<img src="https://placeimg.com/200/500/any/grayscale" height="64" />

<img src="https://placeimg.com/200/500/any/grayscale" class="widthSet" />

<img src="https://placeimg.com/200/500/any/grayscale" class="heightSet" />

另一个为您提供更大灵活性的选项是使用 object-fit 。这允许为 img 设置固定尺寸,同时图像本身可以在定义区域 以多种不同方式呈现。

 img {
    width: 128px;
    height: 128px;
    border: 1px solid hotpink;
}

.fill {
  object-fit: fill;
}

.contain {
  object-fit: contain;
}

.cover {
  object-fit: cover;
}

.scale-down {
  object-fit: scale-down;
}
 <img src="https://placeimg.com/200/500/any/grayscale" class="fill" />

<img src="https://placeimg.com/200/500/any/grayscale" class="contain" />

<img src="https://placeimg.com/200/500/any/grayscale" class="cover" />

<img src="https://placeimg.com/200/500/any/grayscale" class="scale-down" />

原文由 Turnip 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题