DigitalOcean 提供适用于旅程各个阶段的云产品。立即开始使用 $200 免费信用额度!
CSS container-type
属性是容器查询功能的一部分,用于将元素注册为容器,当容器满足某些条件时,可以将样式应用于其他元素。
.parent {
container-type: inline-size;
}
@container (width < 500px) {
.child {
flex-direction: column;
}
}
语法
container-type: normal | size | inline-size;
- 初始值:
normal
- 应用于:所有元素
- 继承:否
- 百分比:N/A
- 计算值:由关键字指定
- 规范顺序:按语法
- 动画:不可动画
值
除了 CSS 全局关键字值,我们目前可以定义三种类型的容器
/* Keyword values */
container-type: normal;
container-type: size;
container-type: inline-size;
/* Global Values */
container-type: inherit;
container-type: initial;
container-type: revert;
container-type: revert-layer;
container-type: unset;
normal
: 这表示该元素是一个容器,可以通过其样式而不是大小进行查询。 从技术上讲,所有元素默认都是容器,因此我们甚至不需要显式分配container-type
来定义一个样式容器。size
: 这是当我们想通过其大小来查询容器时,无论我们讨论的是内联方向还是块方向。inline-size
: 这允许我们通过其内联大小来查询容器,它在标准水平书写模式下等效于width
。这可能是最常用的值,因为我们可以根据元素大小而不是视口大小来建立响应式设计,就像我们通常使用 媒体查询 一样。
container-name
属性有时需要它
从技术上讲,所有元素默认都是容器,只是它们是样式容器,不能通过其大小进行查询。这是因为 container-type
属性的默认值为 normal
,它确保所有元素至少可以按其样式进行查询,即使我们没有显式设置其 container-type
。
但是,如果我们想通过其大小来查询元素,我们必须显式设置 container-type
。
.parent {
container-type: inline-size;
}
我们可以仅使用 container-type
属性将任何元素注册为容器,即使我们没有为其提供 container-name
。在这种情况下,任何 @container
查询都将匹配无名容器。
.parent {
container-type: inline-size;
}
/* This matches the .parent container */
@container (width > 800px) {
article {
display: flex;
}
}
也就是说,如果我们想查询特定容器,我们绝对需要提供 container-name
。如果我们想通过其 size
或 inline-size
来查询该特定容器,那么我们必须带上 container-type
属性。
.parent {
container-name: cards-grid;
container-type: inline-size;
}
/* This matches the .parent container */
@container cards-grid (width > 800px) {
article {
display: flex;
}
}
但是,如果我们只想查询元素的样式,那么就没有必要声明这两个属性,因为所有元素默认都是样式查询,这得益于 container-type: normal
是默认值。
container
简写属性中
它包含在 我们可以通过使用 container
简写属性来避免单独声明 container-type
和 container-name
,该属性将两者合并到一个声明中。
.parent {
container: cards-grid / inline-size;
/* Equivalent to: */
container-name: cards-grid;
container-type: inline-size;
}
规范
container-type
属性在 CSS 包含模块级别 3 规范 中定义,该规范在撰写本文时目前处于编辑草案状态。