正在加载,请稍候…

现代 CSS 布局 2026:容器查询、子网格、级联层和 :has()

掌握现代 CSS 布局技术:容器查询实现组件响应式,CSS Grid 子网格实现对齐布局,级联层控制特异性,以及 :has() 选择器。

现代 CSS 布局 2026:容器查询、子网格、级联层和 :has()

2026 年的 CSS 格局已经解决了多年来需要 JavaScript 变通方法的问题。容器查询、子网格、级联层和 :has() 都已基线可用。

容器查询:基于组件的响应式

媒体查询响应视口宽度。容器查询响应父元素的宽度——实现真正可移植的组件。

/* 步骤 1:定义包含上下文 */
.card-container {
  container-type: inline-size;
  container-name: card;
}

/* 步骤 2:基于容器宽度而非视口设置样式 */
.card {
  display: flex;
  flex-direction: column;
}

@container card (min-width: 400px) {
  .card {
    flex-direction: row;
    gap: 1rem;
  }
  .card__image {
    width: 200px;
    flex-shrink: 0;
  }
}

/* 容器查询单位:cqw = 容器宽度的 1% */
.card__title {
  font-size: clamp(1rem, 3cqw, 2rem);
}

现代 CSS 布局 2026:容器查询、子网格、级联层和 :has() 插图

CSS Grid 子网格:跨卡片对齐

/* 经典问题:卡片标题无法跨卡片对齐 */
/* 使用子网格:卡片共享父级的行轨道 */
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
}

.product-card {
  display: grid;
  grid-row: span 3;            /* 每个卡片跨越 3 行 */
  grid-template-rows: subgrid;  /* 参与父级网格 */
}

/* 现在所有卡片的图像/标题/正文完美对齐 */
.card-image { grid-row: 1; }
.card-title { grid-row: 2; }
.card-body  { grid-row: 3; }

现代 CSS 布局 2026:容器查询、子网格、级联层和 :has() 插图

级联层:终结特异性战争

/* 定义层顺序:后面的层赢得特异性平局 */
@layer base, components, utilities;

@layer base {
  *, *::before, *::after { box-sizing: border-box; }
  body { margin: 0; font-family: system-ui; }
}

@layer components {
  .button {
    padding: 0.5rem 1rem;
    background: var(--color-primary);
    color: white;
  }
}

@layer utilities {
  /* 这些覆盖组件,无论选择器特异性如何 */
  .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; }
}

/* 将第三方 CSS 导入层(它输给我们的层) */
@import url('bootstrap.css') layer(bootstrap);
@layer bootstrap, components;  /* 我们的组件覆盖 Bootstrap */

现代 CSS 布局 2026:容器查询、子网格、级联层和 :has() 插图

:has() 关系选择器

/* 根据子元素有效性设置表单样式 */
.form-group:has(input:invalid) label {
  color: red;
}

/* 卡片布局取决于是否包含图像 */
.card:has(img) {
  grid-template-columns: 200px 1fr;
}
.card:not(:has(img)) {
  grid-template-columns: 1fr;
}

/* 导航:当下拉菜单悬停时淡化其他链接 */
nav:has(.dropdown:hover) .other-links {
  opacity: 0.5;
}

/* 基于子元素数量的自动网格 */
.gallery:has(> :nth-child(4)) { grid-template-columns: repeat(2, 1fr); }
.gallery:has(> :nth-child(5)) { grid-template-columns: repeat(3, 1fr); }

使用 @property 的自定义属性

/* @property 启用类型检查的自定义属性 */
@property --gradient-angle {
  syntax: '<angle>';
  inherits: false;
  initial-value: 0deg;
}

.animated-border {
  background: conic-gradient(
    from var(--gradient-angle),
    var(--color-primary), var(--color-secondary), var(--color-primary)
  );
  animation: rotate 3s linear infinite;
}

@keyframes rotate {
  to { --gradient-angle: 360deg; }  /* 仅在使用 @property 时有效 */
}

容器查询、子网格和级联层共同解决了三个最难的 CSS 布局问题。所有现代浏览器均支持,无需 polyfill。

→ 使用 Color Converter 工具验证你的 CSS 十六进制颜色。