CSSContainerRule: containerQuery 屬性

Baseline 2023
新推出

自 2023 年 9 月起,此功能可在最新的裝置和瀏覽器版本上使用。此功能可能無法在較舊的裝置或瀏覽器上使用。

CSSContainerRule 介面中只讀的 containerQuery 屬性會返回一個字串,該字串表示容器在大小發生變化時進行評估的容器查詢條件,以確定是否應用相關 @container 規則中的樣式。

例如,下面 @container 規則的 containerQuery 屬性值是 (width >= 700px)

css
@container sidebar (width >= 700px) {
  .card {
    font-size: 2em;
  }
}

包含容器查詢的字串。

請注意,該值可能與原始字串不完全相同,因為可能會進行一些規範化處理,例如移除空格。

示例

下面的示例定義了一個未命名的 @container 規則,並顯示了相關的 CSSContainerRule 屬性。CSS 與 @container 示例 根據容器大小設定樣式 中的 CSS 相同。

首先,我們為包含在 post 中的 card (<div>) 定義 HTML。

html
<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>

容器元素的 CSS 指定了容器的型別。然後,如果容器的寬度小於 650px,@container 規則將為包含的元素 "card" 應用新的寬度、字型大小和背景顏色。

html
<style id="example-styles">
  /* A container context based on inline size */
  .post {
    container-type: inline-size;
  }

  /* Apply styles if the container is narrower than 650px */
  @container (width < 650px) {
    .card {
      width: 50%;
      background-color: gray;
      font-size: 1em;
    }
  }
</style>

下面的程式碼透過 ID 獲取與示例關聯的 HTMLStyleElement,然後使用其 sheet 屬性獲取 StyleSheet。從 StyleSheet 中,我們可以獲取新增到該樣式表中的 cssRules 集合。由於我們將 @container 新增為了上面的第二條規則,我們可以透過 cssRules 中的第二個條目(索引為 "1")來訪問相關的 CSSContainerRule。最後,我們記錄下容器名稱和查詢屬性。

js
const exampleStylesheet = document.getElementById("example-styles").sheet;
const exampleRules = exampleStylesheet.cssRules;
const containerRule = exampleRules[1]; // a CSSContainerRule representing the container rule.
log(`CSSContainerRule.containerQuery: "${containerRule.containerQuery}"`);

示例輸出如下所示。日誌部分列出了查詢字串。當頁面寬度在 650px 處過渡時,卡片應該會改變背景。

規範

規範
CSS 條件規則模組第五版
# dom-csscontainerrule-containerquery

瀏覽器相容性

另見