如何用图片填充盒子而不扭曲它

在本指南中,你可以学习一种使 HTML 图片完全填充方框的技术。

¥In this guide you can learn a technique for causing an HTML image to completely fill a box.

使用对象拟合

¥Using object-fit

当你使用 HTML <img> 元素将图片添加到页面时,图片将保持图片文件的大小和纵横比,或者任何 HTML widthheight 属性的大小和纵横比。有时你希望图片完全填满你放置它的框。在这种情况下,你首先需要确定如果图片的长宽比不适合容器,会发生什么情况。

¥When you add an image to a page using the HTML <img> element, the image will maintain the size and aspect ratio of the image file, or that of any HTML width or height attributes. Sometimes you would like the image to completely fill the box that you have placed it in. In that case you first need to decide what happens if the image is the wrong aspect ratio for the container.

  1. 图片应完全填满框,保留纵横比,并裁剪掉太大而无法容纳的一侧的任何多余部分。
  2. 图片应适合框内,背景在太小的一侧显示为条形。
  3. 图片应填充框并拉伸,这可能意味着它以错误的宽高比显示。

object-fit 属性使这些方法中的每一种都成为可能。在下面的示例中,你可以看到使用同一图片时不同的 object-fit 值如何工作。选择最适合你的设计的方法。

¥The object-fit property makes each of these approaches possible. In the example below you can see how different values of object-fit work when using the same image. Select the approach that works best for your design.