此页面 已准备就绪

注意: WebPlatform 项目在 2012 年至 2015 年间由多个维护者支持,现已停止维护。该网站现在可在 github 上找到。

object-fit

摘要

object-fit 属性定义了如何调整替换元素(例如视频或图像)的内容以适应其包含框的尺寸。

概述表

初始值
fill
适用范围
替换元素
继承
媒体
视觉
计算值
按指定
可动画
CSS 对象模型属性
objectFit

语法

  • object-fit: contain
  • object-fit: cover
  • object-fit: fill
  • object-fit: none
  • object-fit: scale-down

fill
替换内容的大小设置为填充元素的框
contain
替换内容的大小设置为在保持其纵横比的同时适应元素的内容框
cover
替换内容的大小设置为在保持其纵横比的同时填充元素的整个内容框
替换内容不会被调整大小以适应元素的内容框
scale-down
根据 ‘none’ 或 ‘contain’ 指定的情况对内容进行调整,选择哪个会导致更小的实际对象尺寸

示例

五个简单的 img 元素。

<!DOCTYPE HTML>
<html lang="en-US">
<head>
  <meta charset="UTF-8">
  <title>Object-fit example</title>
  <link href="content-fit.css" type="text/css" rel="stylesheet">
</head>
<body>

  <img src="/logo/wplogo_pillow_wide_tan.png"
      alt="Webplatform Logo" class="fill"/>
  <img src="/logo/wplogo_pillow_wide_tan.png"
      alt="Webplatform Logo" class="contain"/>
  <img src="/logo/wplogo_pillow_wide_tan.png"
      alt="Webplatform Logo" class="cover"/>
  <img src="/logo/wplogo_pillow_wide_tan.png"
      alt="Webplatform Logo" class="none"/>
  <img src="/logo/wplogo_pillow_wide_tan.png"
      alt="Webplatform Logo" class="scale-down"/>

</body>
</html>

所有五个图像都被强制设置为 150x100 像素,这与图像的原始尺寸(196x77 像素)及其纵横比都不同。

img {
  float: left;
  width: 150px;
  height: 100px;
  border: 1px solid #000;
  margin-right: 1em;
}
.fill {
  object-fit: fill;
  /**
    * This is the default behaviour.
    * The image is forced to fill the whole box,
    * the aspect ratio is ignored.
    **/
}
.contain {
  object-fit: contain;
  /**
    * The whole image will be displayed in the box
    * and scaled down or expanded if necessary.
    * The aspect ratio is maintained.
    **/
}
.cover {
  object-fit: cover;
  /**
    * The whole image is scaled down or expanded till
    * it fills the box completely, the aspect ratio is
    * maintained. This normally results in only part of
    * the image being visible.
    **/
}
.none {
  object-fit: none;
  /**
    * The image keeps it's original size.
    * This may result in not filling the box
    * completely or sticking out of it.
    **/
}
.scale-down {
  object-fit: scale-down;
  /**
    * The result of 'none' and 'contain' is compared
    * and the smaller concrete object is displayed.
   **/
}

查看实时示例

相关规范

CSS Image Values and Replaced Content Module Level 3
W3C 候选推荐标准

参见

相关文章

生成和替换的内容

多媒体

视频