CSS Handbook · 媒体查询

第五章 / 5.3 容器查询

第五章 · 5.3 节

容器查询


媒体查询感知的是"视口",而容器查询感知的是"组件自身所在的父容器"——这让同一个组件无论被放进侧边栏的窄列还是主内容区的宽列,都能各自呈现合适的样式,是真正意义上的"组件级响应式"。

媒体查询的局限

设想一张卡片组件,它可能出现在三栏网格里,也可能出现在单栏侧边栏里。媒体查询只知道浏览器视口有多宽,并不知道这张卡片此刻实际可用的空间有多少——这正是容器查询要解决的问题。

声明容器与查询

第一步,把某个元素声明为"查询容器":

.card-list {
  container-type: inline-size;
  container-name: card-list;
}

第二步,用 @container 针对该容器的尺寸写规则:

@container card-list (min-width: 480px) {
  .card {
    display: grid;
    grid-template-columns: 120px 1fr;
  }
}
提示container-type: inline-size 表示只监听行内方向(通常是宽度)的尺寸变化,这是最常用也性能最优的取值。

容器相对单位

配合容器查询,CSS 还提供了一组相对单位,让字号、间距可以随容器尺寸平滑缩放,而不是在断点处生硬跳变:

单位含义
cqw容器宽度的 1%
cqh容器高度的 1%
cqi容器行内尺寸的 1%
cqb容器块方向尺寸的 1%
.card h3 {
  font-size: clamp(16px, 4cqi, 22px);
}

容器样式查询

更进一步,还可以根据容器自身的自定义属性取值来决定子元素样式,实现"主题随容器变化":

.theme-dark { --surface: dark; }

@container style(--surface: dark) {
  .card { color: #fff; }
}

容器样式查询是较新的能力,实际项目中使用前建议先确认目标浏览器的支持情况。

Chapter 5 · Section 5.3

Container Queries


Media queries sense the "viewport", while container queries sense "the parent container the component itself lives in" — so the same component renders appropriately whether it is placed in a narrow sidebar column or a wide main-content column. This is true "component-level responsiveness".

The Limits of Media Queries

Imagine a card component that may appear in a three-column grid or in a single-column sidebar. Media queries only know how wide the browser viewport is; they do not know how much space this card actually has available at the moment — that is exactly the problem container queries solve.

Declaring Containers and Queries

First, declare an element as a "query container":

.card-list {
  container-type: inline-size;
  container-name: card-list;
}

Second, write rules against that container's size with @container:

@container card-list (min-width: 480px) {
  .card {
    display: grid;
    grid-template-columns: 120px 1fr;
  }
}
Tipcontainer-type: inline-size means the container only listens for size changes along the inline axis (usually width) — the most common and best-performing value.

Container-relative Units

Alongside container queries, CSS provides a set of relative units that let font-size and spacing scale smoothly with the container, instead of jumping abruptly at breakpoints:

UnitMeaning
cqw1% of the container's width
cqh1% of the container's height
cqi1% of the container's inline size
cqb1% of the container's block size
.card h3 {
  font-size: clamp(16px, 4cqi, 22px);
}

Container Style Queries

Going further, you can also decide child-element styles based on the container's own custom-property values, enabling "the theme follows the container":

.theme-dark { --surface: dark; }

@container style(--surface: dark) {
  .card { color: #fff; }
}

Container style queries are a newer capability; before using them in real projects, check the support status of your target browsers.