CSS新特性

发布于:2025-09-15 ⋅ 阅读:(21) ⋅ 点赞:(0)

CSS容器查询

容器查询允许开发者基于父容器尺寸而非视口尺寸应用样式。通过@container规则实现,需先使用container-type定义查询基准:

.parent {
  container-type: inline-size;
}
@container (min-width: 600px) {
  .child { font-size: 1.2rem; }
}

层叠层(Cascade Layers)

通过@layer控制样式优先级,解决特异性冲突。可创建明确的分层结构:

@layer base, components, utilities;
@layer base {
  button { background: red; }
}
@layer utilities {
  .btn { background: blue; } /* 最终生效 */
}

子网格(Subgrid)

扩展CSS Grid功能,允许嵌套网格继承父网格轨道。在grid布局中声明:

.parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
.child {
  grid-column: span 2;
  display: grid;
  grid-template-columns: subgrid; /* 继承父级列轨道 */
}

颜色函数更新

新增oklch()oklab()等感知均匀的颜色空间函数:

.element {
  background: oklch(70% 0.3 150); /* 亮度 色度 色相 */
  color: oklab(0.6 -0.1 -0.2);
}

视口单位扩展

新增动态视口单位适应移动端浏览器UI变化:

  • dvw/dvh:考虑动态工具栏的视口尺寸
  • svw/svh:最小可见视口尺寸
  • lvw/lvh:最大可见视口尺寸

文本换行控制

text-wrap属性提供更精细的排版控制:

p {
  text-wrap: pretty; /* 自动优化换行避免孤行 */
  text-wrap: balance; /* 平衡多行文本宽度 */
}

滚动驱动动画

通过scroll-timeline关联滚动位置与动画:

@keyframes fade {
  to { opacity: 0 }
}
.scroller {
  scroll-timeline: --scroll-track;
}
.target {
  animation: fade auto linear;
  animation-timeline: --scroll-track;
}

嵌套语法

原生CSS支持类似预处理器嵌套写法:

.parent {
  & .child { color: red; }
  @media (width >= 600px) {
    padding: 2rem;
  }
}