Skip to main content Skip to docs navigation
Added in v5.3 View on GitHub

对象匹配(Object fit)

使用对象拟合实用程序可修改替换元素(如<img><video>)内容的大小,以适应其容器。

工作原理

使用我们的响应式 object-fit 实用工具类更改 object-fit属性 的值。该属性会告诉内容以各种方式填充父容器,例如保持纵横比或尽可能拉伸以占据更多空间。

object-fit 值的类使用object-fit-{value} 格式命名。请从以下值中选择:

  • contain
  • cover
  • fill
  • scale (for scale-down)
  • none

示例

被替换元素 添加 object-fit-{value} 类:

Placeholder : Object fit contain Placeholder : Object fit cover Placeholder : Object fit fill Placeholder : Object fit scale down Placeholder : Object fit none
html
<img src="..." class="object-fit-contain border rounded" alt="...">
<img src="..." class="object-fit-cover border rounded" alt="...">
<img src="..." class="object-fit-fill border rounded" alt="...">
<img src="..." class="object-fit-scale border rounded" alt="...">
<img src="..." class="object-fit-none border rounded" alt="...">

响应式

对于以下断点缩写,每个 object-fit 值还存在响应变化,其格式为.object-fit-{breakpoint}-{value}: smmdlgxlxxl`。可以根据需要组合这些类,以实现各种效果。

Placeholder : Contain on sm Placeholder : Contain on md Placeholder : Contain on lg Placeholder : Contain on xl Placeholder : Contain on xxl
html
<img src="..." class="object-fit-sm-contain border rounded" alt="...">
<img src="..." class="object-fit-md-contain border rounded" alt="...">
<img src="..." class="object-fit-lg-contain border rounded" alt="...">
<img src="..." class="object-fit-xl-contain border rounded" alt="...">
<img src="..." class="object-fit-xxl-contain border rounded" alt="...">

视频

.object-fit-{value} 和响应式 object-fit-{breakpoint}-{value} 工具也适用于<video> 元素。

<video src="..." class="object-fit-contain" autoplay></video>
<video src="..." class="object-fit-cover" autoplay></video>
<video src="..." class="object-fit-fill" autoplay></video>
<video src="..." class="object-fit-scale" autoplay></video>
<video src="..." class="object-fit-none" autoplay></video>

CSS

Sass utilities API

对象拟合实用程序在我们的实用程序 API 中声明,该 API 位于 scss/_utilities.scss了解如何使用实用程序 API

"object-fit": (
  responsive: true,
  property: object-fit,
  values: (
    contain: contain,
    cover: cover,
    fill: fill,
    scale: scale-down,
    none: none,
  )
),