CSS Container Queries 完全指南

Choyeon· 2026年9月1日· 2 分钟阅读· 390 阅读· 511 字· 1,625 字符
CSS Container Queries 完全指南

多年来响应式只能依赖媒体查询(基于视口),但组件化时代组件可能被放置在任意宽度区域。Container Queries + :has() 开启真正组件级响应式。

Container Queries 容器查询

给父容器声明 container-type: inline-size,子元素即可用 @container 根据父容器宽度切换布局,搭配 cqw/cqh/cqi 容器相对单位,实现上下文自适应。

.card-wrapper { container-type: inline-size; container-name: productCard; }
.product-card {
  display: flex; flex-direction: column; padding: 1rem;
  border: 1px solid var(--border); border-radius: 12px; transition: all 0.2s;
}
.product-image { width: 100%; aspect-ratio: 4 / 3; }
.product-info { display: grid; grid-template-columns: 1fr; gap: 0.5rem; }
.product-title { font-size: 1rem; }
.product-price { font-weight: 700; color: var(--primary); }

@container productCard (min-width: 400px) {
  .product-card { flex-direction: row; gap: 1rem; }
  .product-image { width: 45%; aspect-ratio: 1 / 1; }
  .product-title { font-size: 1.125rem; }
}
@container productCard (min-width: 640px) {
  .product-card { padding: 1.5rem; }
  .product-info { grid-template-columns: 2fr 1fr; }
  .product-title { font-size: 1.25rem; grid-row: span 2; }
  .product-price { font-size: 1.5rem; align-self: end; }
}

.product-card:has(.out-of-stock) { opacity: 0.7; filter: grayscale(0.3); }
.product-card:has(input[type="checkbox"]:checked) {
  border-color: var(--primary);
  box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 30%, transparent);
}
.product-wrapper:has(> .product-card:hover) .product-card:not(:hover) {
  transform: scale(0.98); opacity: 0.85;
}

.hero-title { font-size: clamp(1.5rem, 8cqi, 3rem); line-height: 1.1; }
.hero-cta { padding: 0.05cqw 0.2cqh; border-radius: 0.1cqh; }

:has() 父选择器

长久以来 CSS 只能祖先 → 后代单向选择,:has() 打破这个限制。根据子元素是否存在/状态设置祖先样式,实现悬停兄弟弱化、表单验证反馈、空状态样式等。

特性 媒体查询 @media 容器查询 @container :has() 选择器
触发依据 视口尺寸 父容器尺寸 后代元素状态
适用层级 页面级 组件级 任意祖先层级
单位 vw/vh/vmin cqw/cqh/cqi -
浏览器支持 全支持 现代浏览器 Chrome/Safari/Firefox

最佳实践

不要滥用 :has() 嵌套过深,避免 :has(*:hover) 这类全量匹配。容器查询配合 container-name 防多实例冲突。

本文作者

评论 (0)

暂无评论,来抢沙发吧。