流暢擴充

網頁功能: 容器查詢 (大小)

總覽

流暢縮放功能可讓元件根據目前尺寸,調整內部比例 (例如字型大小和間距)。與在固定中斷點之間跳轉相比,這種做法能讓設計更具一致性。

過去,流暢擴充是使用可視區域單位 (根據螢幕大小縮放) 達成,但現代容器查詢單位可讓元件根據父項容器縮放。這樣一來,無論元件在版面配置中的位置為何,都能呈現良好效果,進而提升元件隔離性和可重複使用性。

導入作業

1. 定義容器

如要使用容器查詢單位,您必須先在父項元素上定義容器情境。

.component-wrapper {
  /* Define the container type. Use 'inline-size' for width-based scaling. */
  /* You can also use 'size' for both width and height, but it requires explicit sizing. */
  container-type: inline-size;
  
  /* Optional: Name the container for specific targeting */
  container-name: fluid-card;
}

2. 使用容器查詢單位

使用容器查詢單位 (cqi、cqb 等),根據容器尺寸設定大小。

  • cqi:容器內嵌大小 (水平書寫模式中的寬度) 的 1%。
  • cqb:容器區塊大小 (水平書寫模式的高度) 的 1%。

注意:容器單元可直接用於任何資源,不需 @container 查詢規則。系統會根據已定義 container-type 的最近祖系自動解析。

.component-title {
  /* Scale font size based on container width */
  /* 10cqi means 10% of the container's width */
  font-size: 10cqi;
}

.component-body {
  /* Scale padding based on container width */
  padding: 5cqi;
}

3. 使用 clamp() 限制值

為避免尺寸過小或過大,請使用 CSS clamp() 函式。這會影響使用者縮放或調整基本字型大小的能力。為確保文字符合無障礙指南,大小上限不得超過大小下限的 2.5 倍。

.component-title {
  /* Clamp font size between 1rem and 2.5rem, scaling with 5% of container width */
  font-size: clamp(1rem, 5cqi, 2.5rem);
}

備用策略

如果瀏覽器不支援容器查詢,請使用可視區域單位或標準媒體查詢提供備用方案。

.component-title {
  /* Fallback for browsers that do not support container units */
  font-size: clamp(1rem, 5vw, 2.5rem);
}

@supports (font-size: 1cqi) {
  .component-title {
    /* Use container units where supported */
    font-size: clamp(1rem, 5cqi, 2.5rem);
  }
}

這個備用方案可確保文字仍會縮放,但會根據螢幕寬度 (而非元件寬度) 縮放。請務必測試,確認這項功能適用於您的用途。