跳至主要内容 跳至文档导航

对象拟合(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-{breakpoint}-{value}的每个object-fit值也存在响应变体: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="...">

Video

.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>

实用程序 API

Object fit 实用程序在我们的实用程序 API 中的scss/_utilities.scss中声明。了解如何使用实用程序 API

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