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

瀏覽器相容性

另見