interpolate-size

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

interpolate-size CSS 属性允许您启用 动画过渡,使 <length-percentage> 值与 固有尺寸 值(例如 autofit-contentmax-content)之间可以进行动画和过渡。

当对非盒模型 CSS 属性(例如 transform)进行动画处理不是一个可行的解决方案时,此属性通常用于在 <length-percentage> 与其内容的完整尺寸之间对容器的 width 和/或 height 进行动画处理(即在“关闭”和“打开”或“隐藏”和“显示”状态之间)。

注意:interpolate-size 所选择的行为不能在整个网络中默认启用,因为许多网站使用假设固有尺寸值不能动画化的样式表。默认启用它会导致一些向后兼容性问题(请参阅相关的 CSS WG 讨论)。

语法

css
/* Keyword values */
interpolate-size: allow-keywords;
interpolate-size: numeric-only;

/* Global values */
interpolate-size: inherit;
interpolate-size: initial;
interpolate-size: revert;
interpolate-size: revert-layer;
interpolate-size: unset;

allow-keywords

启用 <length-percentage> 值和固有尺寸值之间的插值,以允许两者之间进行动画。

numeric-only

默认行为 — 固有尺寸值不能进行插值。

描述

设置 interpolate-size: allow-keywords 可以在 <length-percentage> 值和固有尺寸值之间启用插值。请注意,它不启用两个固有尺寸值之间的动画。动画的一端必须是 <length-percentage>

interpolate-size 值是继承的,因此可以通过将其设置在文档根元素上,为整个文档启用动画到(或从)固有尺寸值。

css
:root {
  interpolate-size: allow-keywords;
}

如果您想限制范围,可以将其设置在相关的容器元素上。以下仅为 <main> 及其后代启用固有尺寸的插值。

css
main {
  interpolate-size: allow-keywords;
}

注意:calc-size() 函数的返回值也可以插值。实际上,在属性值中包含 calc-size() 会自动将 interpolate-size: allow-keywords 应用于选择。然而,由于 interpolate-size 如上所述是继承的,因此在大多数情况下,它是启用固有尺寸动画的首选解决方案。您应该仅在固有尺寸动画还需要计算的情况下才使用 calc-size() 来启用它们。

可以插值的值

目前可以启用动画的以下固有值

正式定义

初始值numeric-only
应用于所有元素
继承性
计算值同指定值
动画类型不可动画化

正式语法

interpolate-size = 
numeric-only |
allow-keywords

示例

基本 interpolate-size 用法

此示例演示如何在文档上设置 interpolate-size: allow-keywords 以启用涉及固有尺寸的动画。该演示展示了一个角色徽章/“名牌”,可以悬停或聚焦以显示有关角色的信息。显示通过在设定长度和 max-content 之间的 height 过渡来处理。

HTML

HTML 包含一个 <section> 元素,其上设置了 tabindex="0",因此它可以接收键盘焦点。<section> 包含 <header><main> 元素,每个元素都有自己的子内容。

html
<section tabindex="0">
  <header>
    <h2>Tanuki</h2>
  </header>
  <main>
    <p>Tanuki is the silent phantom of MDN.</p>
    <ul>
      <li><strong>Height</strong>: 3.03m</li>
      <li><strong>Weight</strong>: 160kg</li>
      <li><strong>Tech Fu</strong>: 7</li>
      <li><strong>Bad Jokes</strong>: 9</li>
    </ul>
  </main>
</section>

CSS

在 CSS 中,我们首先在 :root 上设置 interpolate-size: allow-keywords,以便为整个文档启用它。

css
:root {
  interpolate-size: allow-keywords;
}

然后,我们将 <section>height 设置为 2.5rem,将 overflow 设置为 hidden,以便默认只显示 <header>,然后指定一个 transition,在状态更改期间在 1 秒内动画 <section>height。最后,我们将 :hover:focus 上的 <section> height 设置为 max-content

css
section {
  height: 2.5rem;
  overflow: hidden;
  transition: height ease 1s;
}

section:hover,
section:focus {
  height: max-content;
}

为了简洁起见,其余的 CSS 已隐藏。

结果

尝试将鼠标悬停在 <section> 上或通过键盘聚焦它 — 它将动画到其完整高度,显示所有内容。

规范

规范
CSS 值和单位模块 Level 5
# interpolate-size

浏览器兼容性

另见