YL

DESIGN SYSTEM

容器查询Container Queries

组件按"自己容器"的宽度自适应,而不是按视口——放进哪都能用。

效果预览

宽容器 → 横排
窄 → 竖
同一组件,容器宽度不同则布局不同

适合用在哪

卡片组件、可复用模块、组件库;取代大量媒体查询。

容易踩的坑

  • 在组件自身而非父级设 container-type,@container 查询永远不匹配。
  • container-type:size 未给定高度,容器高度塌陷为 0、内容消失。
  • 容器内的 position:fixed 浮层被新包含块限制,弹窗只显示在卡片内部。

设计提示词 · Prompt

容器查询(Container Queries):父容器 container-type:inline-size,内部用 @container (min-width: 480px) 写样式——组件根据容器而非视口响应。一个卡片在侧栏里是竖排、拖进宽栏自动变横排,无需外层干预。这是组件化响应式的正解:媒体查询管页面布局(断点),容器查询管组件形态。配套 cqw/cqh 单位(容器宽度的 1%)做流式字号。注意 container-type 会建立新的包含块,position:fixed 子元素会被影响。兼容性已足够好(2023+ 全线支持),新项目放心用。
Container Queries: Set container-type:inline-size on the parent container and write styles inside with @container (min-width: 480px) — the component responds to its container rather than the viewport. A card stacks vertically in a sidebar and automatically switches to horizontal when dropped into a wide column, with no outer intervention. This is the right answer for component-level responsiveness: media queries handle page layout (breakpoints), container queries handle component form. Use the cqw/cqh units (1% of the container width) for fluid type. Note that container-type establishes a new containing block, which affects position:fixed children. Browser support is good enough (fully supported since 2023+); use it confidently in new projects.

常见搭配

同一页面里经常和「容器查询」一起出现的模式,可以收藏后用「组合收藏为整页提示词」一起交给 AI。

演示 HTML 结构

<div class="s d-cqdemo">
  <div class="d-cq__card d-cq__card--wide">
    <span class="d-cq__av"></span>
    <span class="d-cq__info"><i style="width:52%"></i><i style="width:30%"></i></span>
    <span class="d-cq__btn">宽容器 → 横排</span>
  </div>
  <div class="d-cq__card" style="max-width:150px">
    <span class="d-cq__av"></span>
    <span class="d-cq__info"><i style="width:80%"></i><i style="width:52%"></i></span>
    <span class="d-cq__btn">窄 → 竖</span>
  </div>
  <span class="d-cq__cap">同一组件,容器宽度不同则布局不同</span>
</div>

标签