🗒️@container
container query,容器查询
container query 是 media query 的替代方案:
- media query 是基于 viewport size 
- container query 是基于元素的 container size 
用法
要使用容器查询:在元素上声明 containment context(包含上下文),以便让浏览器知道待会可能想要查询该容器的尺寸。
container-type: size | inline-size | normal;举例:
.post {
    /* 声明包含上下文 */
    container-type: inline-size;
}
/* 定义容器查询(基于具有包含上下文的最近祖先) */
@container (width < 700px) {
}<article class="post">
    <section class="card">
        <h2>Title</h2>
        <p>xxx</p>
    </section>
</article>.post {
    /* 声明包含上下文 */
    container-type: inline-size;
}
.post .card {
    color: green;
}
/* 定义容器查询 */
@container (width < 700px) {
    .post .card {
        color: red;
    }
}在容器查询的条件中,可以用:
- width,- height
- block-size,- inline-size
- aspect-ratio
- orientation
- style()实验中
相对于查询容器的长度单位:
- cqw,- cqh
- cqi
- cqb
- cqmin cqi,- cqmax cqi
命名包含上下文
在上一节中,容器查询是基于“具有包含上下文的最近祖先”应用的样式。
还可以给包含上下文定义一个名字,然后针对特定容器来设置容器查询。
.post {
    container-type: inline-size;  /* 声明包含上下文 */
    container-name: sidebar;      /* 命名 */
    
    container: sidebar / inline-size;    /* 缩写 */
}
/* 定义容器查询,针对特定容器来定义 */
@container sidebar (width < 700px) {
}主要参考
Last updated