CSS容器查询实战:5个自适应组件开发技巧
1. 基础容器查询
创建根据容器大小变化的卡片组件:
.card-container {
container-type: inline-size;
}
.card {
padding: 1rem;
background: white;
border-radius: 8px;
}
@container (min-width: 400px) {
.card {
display: flex;
gap: 1rem;
}
}
@container (min-width: 600px) {
.card {
padding: 2rem;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
}
.demo-card {
padding: 1rem;
background: white;
border-radius: 8px;
margin: 10px 0;
}
@container (min-width: 400px) {
.demo-card {
display: flex;
gap: 1rem;
}
}
@container (min-width: 600px) {
.demo-card {
padding: 2rem;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
}
卡片标题
根据容器宽度自动调整布局
2. 容器查询单位
使用cqw/cqh等容器相对单位:
.widget {
container-type: size;
}
.widget-content {
font-size: clamp(1rem, 3cqw, 1.5rem);
padding: clamp(0.5rem, 2cqh, 1rem);
}
@container (aspect-ratio > 1/1) {
.widget-content {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
3. 容器查询与网格布局
动态调整网格列数:
.product-grid {
container-type: inline-size;
display: grid;
gap: 1rem;
}
@container (min-width: 500px) {
.product-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@container (min-width: 800px) {
.product-grid {
grid-template-columns: repeat(3, 1fr);
}
}
4. 容器命名与特定查询
针对特定容器进行样式调整:
.sidebar {
container-type: inline-size;
container-name: sidebar;
}
.main-content {
container-type: inline-size;
container-name: main;
}
@container sidebar (min-width: 300px) {
.navigation {
display: flex;
flex-direction: column;
}
}
@container main (min-width: 700px) {
.article {
column-count: 2;
}
}
技术 | 媒体查询 | 容器查询 |
---|---|---|
响应对象 | 视口 | 容器 |
组件复用 | 受限 | 自由 |
设计系统 | 全局 | 模块化 |
5. 实战:自适应数据表格
根据容器尺寸优化表格显示:
.table-container {
container-type: inline-size;
}
.data-table {
width: 100%;
}
@container (max-width: 600px) {
.data-table thead {
display: none;
}
.data-table tr {
display: block;
margin-bottom: 1rem;
}
.data-table td {
display: flex;
justify-content: space-between;
}
.data-table td::before {
content: attr(data-label);
font-weight: bold;
padding-right: 1rem;
}
}
CSS容器查询为现代前端开发带来了真正的组件级响应式能力,特别适合设计系统和复杂应用的开发。