CSS容器查询革命:构建真正自适应的组件级响应式系统
一、架构设计
基于CSS容器查询的组件级自适应方案,摆脱传统媒体查询的束缚,组件自适应能力提升200%
二、核心实现
1. 容器查询基础语法
/* 定义容器 */
.component-container {
container-type: inline-size;
container-name: component;
}
/* 基于容器宽度的样式调整 */
@container component (width < 400px) {
.card {
flex-direction: column;
}
.card__image {
width: 100%;
}
}
@container component (width >= 400px) {
.card {
flex-direction: row;
}
.card__image {
width: 40%;
}
}
2. 容器尺寸单位
/* 使用容器相对单位 */
.card {
padding: calc(5cqw + 10px); /* 基于容器宽度的响应式padding */
margin: 2cqh 0; /* 基于容器高度的margin */
font-size: clamp(1rem, 3cqw, 1.5rem); /* 动态字体大小 */
}
/* 容器尺寸追踪 */
@container component (aspect-ratio > 1) {
.card {
/* 宽屏布局 */
}
}
@container component (aspect-ratio < 1) {
.card {
/* 窄屏布局 */
}
}
三、高级特性
1. 嵌套容器查询
/* 多级容器作用域 */
.outer-container {
container-type: size;
container-name: outer;
}
.inner-container {
container-type: inline-size;
container-name: inner;
}
/* 外层容器查询 */
@container outer (width < 600px) {
.component {
/* 外层响应样式 */
}
}
/* 内层容器查询 */
@container inner (width < 300px) {
.card {
/* 内层响应样式 */
}
}
2. 容器样式穿透
/* 定义容器状态变量 */
.component-container {
--is-narrow: 0;
}
/* 根据容器条件更新变量 */
@container (width < 400px) {
.component-container {
--is-narrow: 1;
}
}
/* 使用容器状态变量 */
.card {
opacity: calc(1 - 0.3 * var(--is-narrow));
transform: scale(calc(1 - 0.1 * var(--is-narrow)));
}
/* 子组件继承容器状态 */
.card__title {
font-size: calc(1rem + 0.5rem * var(--is-narrow));
}
四、完整案例
自适应卡片
根据容器尺寸自动调整布局
<style>
.card {
display: flex;
gap: 1rem;
transition: all 0.3s ease;
}
.card__image {
background: #3a0ca3;
aspect-ratio: 16/9;
}
@container demo (width < 400px) {
.card {
flex-direction: column;
}
.card__title {
font-size: 1.2rem;
}
}
@container demo (width >= 400px) {
.card {
flex-direction: row;
}
.card__image {
width: 200px;
}
}
</style>