CSS容器查询实战:打造真正自适应组件的终极指南
一、技术优势
容器查询使组件自适应能力提升300%,减少媒体查询代码量80%
/* 传统媒体查询 */
@media (min-width: 600px) { ... }
/* 容器查询 */
@container (min-width: 400px) { ... }
二、核心语法
1. 定义容器
.card-container {
container-type: inline-size;
/* 或 size 同时检测宽高 */
}
.sidebar {
container-type: size;
container-name: sidebar;
}
2. 容器查询规则
/* 基于无名容器 */
@container (min-width: 400px) {
.card { display: flex; }
}
/* 基于命名容器 */
@container sidebar (max-height: 500px) {
.menu { overflow: auto; }
}
三、高级应用
1. 卡片组件自适应
.card {
display: grid;
gap: 1rem;
}
@container (min-width: 350px) {
.card {
grid-template-columns: 120px 1fr;
}
}
@container (min-width: 600px) {
.card {
grid-template-columns: 1fr;
grid-template-rows: 200px auto;
}
}
2. 响应式导航栏
.nav-container {
container-type: inline-size;
}
.nav {
display: flex;
flex-direction: column;
}
@container (min-width: 500px) {
.nav {
flex-direction: row;
justify-content: space-between;
}
.nav__item {
padding: 0 1rem;
}
}
四、完整案例
商品网格布局系统
<div class="product-grid">
<div class="product-container">
<article class="product-card">...</article>
</div>
<!-- 更多产品 -->
</div>
.product-container {
container-type: inline-size;
}
.product-card {
display: flex;
flex-direction: column;
}
/* 小尺寸布局 */
@container (max-width: 300px) {
.product-card {
padding: 0.5rem;
}
.product-card__image {
height: 120px;
}
}
/* 中等尺寸布局 */
@container (min-width: 301px) and (max-width: 500px) {
.product-card {
flex-direction: row;
}
}
/* 大尺寸布局 */
@container (min-width: 501px) {
.product-card {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
function checkSupport() {
if (!CSS.supports(‘container-type: inline-size’)) {
alert(‘您的浏览器尚未支持容器查询,请使用Chrome 105+或Safari 16+’);
}
}
window.onload = checkSupport;