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

浏览器兼容性

另见