CSS Container Queries实战:5个元素级响应式设计技巧
1. 基础容器查询
创建响应父元素尺寸的卡片组件:
.card-container {
container-type: inline-size;
}
@container (max-width: 500px) {
.card {
flex-direction: column;
}
}
自适应卡片
根据容器宽度改变布局
2. 多条件查询
组合多个查询条件:
@container (min-width: 300px) and (max-width: 600px) {
/* 中等尺寸样式 */
}
@container (width > 600px) {
/* 大尺寸样式 */
}
3. 容器查询单位
使用cqw/cqh单位:
.element {
/* 基于容器宽度的10% */
width: 10cqw;
/* 基于容器高度的5% */
padding: 5cqh;
}
4. 命名容器
为容器指定名称:
.sidebar {
container-type: inline-size;
container-name: sidebar;
}
@container sidebar (width > 300px) {
/* 侧边栏特定样式 */
}
特性 | 媒体查询 | 容器查询 |
---|---|---|
响应对象 | 视口尺寸 | 元素尺寸 |
组件复用 | 受限 | 高度可复用 |
布局控制 | 全局 | 局部 |
5. 实战:自适应产品网格
创建完全自适应的产品展示:
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
container-type: inline-size;
}
@container (width = 600px) {
.product-card {
grid-template-columns: 1fr 2fr;
}
}
CSS容器查询为现代响应式设计提供了革命性的解决方案,特别适合卡片组件、网格布局、侧边栏等需要根据容器尺寸自适应调整的场景,能大幅提升组件的复用性和灵活性。