CSS容器查询实战指南:响应式设计的新维度
一、容器查询 vs 媒体查询
容器查询(Container Queries)允许组件根据容器尺寸而非视口调整样式:
/* 传统媒体查询 */
@media (min-width: 768px) {
.card { /* 基于视口宽度 */ }
}
/* 容器查询 */
.card-container {
container-type: inline-size;
}
@container (min-width: 400px) {
.card { /* 基于容器宽度 */ }
}
二、容器查询核心语法
卡片标题
内容会根据容器宽度自动调整布局
.component {
container-type: inline-size; /* 或 size */
container-name: sidebar; /* 可选命名 */
}
/* 基础样式 */
.card { display: block; }
/* 容器查询 */
@container (min-width: 500px) {
.card { display: flex; }
}
@container sidebar (min-width: 700px) {
.card { border-left: 4px solid blue; }
}
三、实际应用案例
1. 自适应导航栏
.nav-container {
container-type: inline-size;
}
@container (max-width: 600px) {
.navbar { flex-direction: column; }
.menu { display: none; }
.hamburger { display: block; }
}
2. 智能网格布局
.grid-container {
container-type: inline-size;
display: grid;
gap: 1rem;
}
@container (min-width: 300px) {
.grid-container { grid-template-columns: repeat(2, 1fr); }
}
@container (min-width: 600px) {
.grid-container { grid-template-columns: repeat(3, 1fr); }
}
四、容器查询单位
新增的容器相对单位:
- cqw:容器宽度的1%
- cqh:容器高度的1%
- cqi:容器内联尺寸的1%
- cqb:容器块尺寸的1%
- cqmin:cqi或cqb中较小的值
- cqmax:cqi或cqb中较大的值
.responsive-text {
font-size: clamp(1rem, 3cqi, 2rem);
}
五、性能优化技巧
- 优先使用
inline-size
而非size
- 避免嵌套过深的容器查询
- 配合CSS变量使用减少重复计算
- 使用
container-name
提高可读性
:root {
--breakpoint-sm: 400px;
--breakpoint-md: 700px;
}
@container (min-width: var(--breakpoint-sm)) {
/* 小尺寸样式 */
}
六、浏览器支持与降级方案
目前主流浏览器均已支持,兼容方案:
/* 现代浏览器 */
.card { /* 容器查询样式 */ }
/* 不支持时的降级样式 */
@supports not (container-type: inline-size) {
.card { /* 传统响应式样式 */ }
}
或使用Polyfill:container-query-polyfill
七、最佳实践总结
- 组件库开发优先使用容器查询
- 复杂页面结合媒体查询使用
- 使用命名容器提高可维护性
- 性能敏感页面谨慎使用size类型
- 配合CSS网格和Flexbox实现最佳效果