CSSContainerRule: containerName 屬性

Baseline 2023
新推出

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

CSSContainerRule 介面的只讀 containerName 屬性代表關聯的 CSS @container at-rule 的容器名稱。

例如,下面 @containercontainerName 值為 sidebar

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

一個字串,其中包含與此 CSSContainerRule 關聯的 @containercontainer-name。如果 @container命名,則函式返回空字串 ("")。

示例

下面的示例定義了一個命名的 @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 指定了容器的型別,也可能指定一個名稱。卡片有一個預設的字型大小,如果寬度大於 700px,則會被命名為 sidebar@container 覆蓋。

html
<style id="example-styles">
  .post {
    container-type: inline-size;
    container-name: sidebar;
  }

  /* Default heading styles for the card title */
  .card h2 {
    font-size: 1em;
  }

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

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

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

示例輸出如下所示。日誌部分列出了容器名稱字串。當頁面寬度超過 700px 時,卡片部分中的標題應該會增大一倍。

規範

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

瀏覽器相容性

另見