CSS 的 container-name 属性指定了容器查询中@container规则将使用的可查询容器名称列表。容器查询负责根据具有包含上下文的最近祖先或父级的大小将样式应用于元素。
可能的值
container-name 属性只能有一个值,如下所示:
- <container-name>:区分大小写的字符串,用于标识容器。在设置 container-name 时,有几个条件适用:
以下条件适用:
- 可以使用任何有效的 <custom-ident>,但不能等于默认值。
- 名称值不得用引号括起来。
- 允许在开头提供带有破折号的标识,表示用户定义的标识符,例如 --container-name-sample。
- 允许使用空格分隔多个值。
适用于
所有 HTML 元素。
语法
container-name = none | <custom-ident>+
CSS container-name - 基本示例
以下示例演示了使用 container-name 属性命名容器的方法。
<html>
<head>
<style>
.card {
margin: 10px;
border: 2px dotted;
font-size: 1.5em;
width: 500px;
}
.post {
border: 2px solid red;
}
/* A container context based on inline size */
.post {
container-type: inline-size;
container-name: sample;
}
/* Styles to be applied if the container's (here container is the div element, with class = .post)
min-width is 400px */
@container sample (min-width: 400px) {
p {
visibility: hidden;
}
}
</style>
</head>
<body>
<div class="post" >
<div class="card">
<h2>Card title</h2>
<p>Card content Visible Now</p>
</div>
</div>
</body>
</html>
上面的示例是一个容器查询,当最小宽度为 400px 时,该查询将应用于 .post 元素的内容。
调整窗口大小时以查看效果