CSS 知识详解

从层叠规则到现代布局,从自定义属性到容器查询,系统梳理 CSS 全栈知识,涵盖 W3C 2025 最新特性,助你写出优雅、高性能的样式代码。


目录

  1. 什么是 CSS
  2. 语法与引入方式
  3. 层叠与继承
  4. 选择器优先级
  5. CSS 选择器大全
  6. 伪类与伪元素
  7. CSS 盒模型
  8. Display 与定位
  9. Flexbox 弹性布局
  10. Grid 网格布局
  11. 字体与文本
  12. 颜色与背景
  13. 变换与过渡
  14. CSS 动画
  15. 自定义属性(变量)
  16. 响应式设计
  17. 现代 CSS 特性
  18. 最佳实践

一、什么是 CSS

CSS(Cascading Style Sheets,层叠样式表)是用于描述 HTML 文档视觉呈现的语言。它与 HTML(结构)、JavaScript(行为)共同构成 Web 三层架构的样式层。

三大核心机制

机制 说明
层叠 Cascade 多个来源的样式规则按特定算法合并,优先级高的规则覆盖低的
继承 Inherit 部分属性(如 font、color)会从父元素传递给子元素,减少重复代码
特异性 Specificity ID > 类/属性/伪类 > 标签/伪元素,数值越高优先级越高

📋 W3C CSS Snapshot 2025: W3C 每年发布 CSS 快照文档,汇总当前所有稳定的 CSS 模块规范。CSS 已从单一规范演进为 50+ 独立模块,浏览器实现程度各异。


二、语法与引入方式

基本语法

/* 选择器 { 属性: 值; } */

h1 {
  color: tomato;
  font-size: 2rem;
  margin-bottom: 16px;
}

/* 分组选择器 */
h1, h2, h3 {
  font-family: serif;
}

/* @规则 */
@media (max-width: 768px) {
  h1 { font-size: 1.5rem; }
}

四种引入方式

<!-- ① 外部样式表(推荐):放在 <head> 中 -->
<link rel="stylesheet" href="style.css" />

<!-- ② 内部样式:放在 <style> 标签中 -->
<style>
  body { margin: 0; }
</style>

<!-- ③ 内联样式:直接写在元素 style 属性上(最高优先级,不推荐滥用) -->
<p style="color: red; font-size: 14px;">文字</p>
/* ④ @import:在 CSS 文件中引入另一个 CSS(会阻塞渲染,慎用)*/
@import url('variables.css');

✅ 最佳实践: 优先使用外部样式表,利用浏览器缓存。将关键 CSS(首屏必需的少量样式)内联到 <head> 以提升 LCP 指标,其余通过 <link rel="preload"> 异步加载。


三、层叠(Cascade)与继承

样式来源优先级(从高到低)

优先级 来源 说明
最高 用户 !important 用户代理或用户浏览器设置,极少见
作者 !important 开发者在 CSS 中声明的 !important
动画样式 CSS Animation 动画过程中的计算值
作者普通样式 开发者编写的普通 CSS 规则(最常用)
用户普通样式 用户自定义浏览器样式
最低 浏览器默认样式 User-Agent Stylesheet,如 h1 默认 font-size

@layer 层叠层(CSS 2022+)

/* 定义层叠层,后定义的层优先级更高 */
@layer reset, base, components, utilities;

@layer reset {
  * { box-sizing: border-box; margin: 0; }
}

@layer components {
  .btn { padding: 8px 16px; }
}

@layer utilities {
  .p-4 { padding: 1rem; } /* utilities 层优先级最高 */
}

可继承属性 vs 不可继承属性

可继承属性(举例) 不可继承属性(举例)
colorfont-*line-heighttext-alignletter-spacingword-spacingvisibilitycursorlist-style marginpaddingborderbackgroundwidthheightdisplaypositionfloatbox-shadow

继承控制关键字

.child {
  color: inherit;   /* 强制继承父元素的值 */
  color: initial;   /* 重置为浏览器默认初始值 */
  color: unset;     /* 可继承属性→inherit;不可继承→initial */
  color: revert;    /* 回退到浏览器默认样式(UA stylesheet)*/

  /* all 简写:一次性重置/继承所有属性 */
  all: revert;
}

四、选择器优先级(Specificity)

优先级用三位数 (A, B, C) 表示,从左到右逐位比较,数字越大优先级越高。

选择器 A(ID) B(类/属性/伪类) C(标签/伪元素) 说明
* { } 0 0 0 通配符,无权重
div { } 0 0 1 标签选择器
.btn { } 0 1 0 类选择器
div.btn:hover { } 0 2 1 类 + 伪类 + 标签
#header .nav a { } 1 1 1 ID + 类 + 标签
style="..." 内联样式,约等于 1000
!important 覆盖一切(谨慎使用)

⚠️ 避免 !important: 过度使用会导致样式无法维护。正确做法是提升选择器特异性或使用 CSS @layer 管理优先级顺序。
注意::where() 伪类的特异性永远为 0,:is() 的特异性取其参数中最高的那个。


五、CSS 选择器大全

基础选择器

选择器 说明
* 通配选择器,匹配所有元素(权重为 0)
div 类型/标签选择器,匹配指定标签名的所有元素
.class 类选择器,匹配拥有该 class 的元素,可叠加 .a.b
#id ID 选择器,匹配 id 属性值的元素,页面内唯一
[attr] 属性选择器,见下方详细列表

组合选择器

A B      { /* 后代选择器:A 内部所有 B(含嵌套)*/ }
A > B    { /* 子代选择器:A 的直接子元素 B */ }
A + B    { /* 相邻兄弟:紧接在 A 后的第一个 B */ }
A ~ B    { /* 通用兄弟:A 后所有的 B(同级)*/ }
A, B     { /* 分组:A 和 B 都应用同一规则 */ }

属性选择器

[href]             { /* 存在 href 属性 */ }
[type="text"]      { /* 属性值精确匹配 */ }
[class~="btn"]     { /* 属性值列表中含 btn(空格分隔)*/ }
[lang|="zh"]       { /* 值等于 zh 或以 zh- 开头 */ }
[href^="https"]    { /* 值以 https 开头 */ }
[href$=".pdf"]     { /* 值以 .pdf 结尾 */ }
[title*="CSS"]     { /* 值中包含 CSS */ }
[class*="btn" i]   { /* i 标志:不区分大小写 */ }

现代函数式选择器

/* :is() — 匹配列表中任意选择器,权重取最高 */
:is(h1, h2, h3) { margin-top: 24px; }

/* :where() — 同 :is(),但权重恒为 0 */
:where(article, section) p { line-height: 1.8; }

/* :not() — 排除匹配的元素 */
li:not(:last-child) { border-bottom: 1px solid #eee; }

/* :has() — 父选择器 ⭐ CSS 2023+ 全浏览器支持 */
/* 含有 img 子元素的 figure 加圆角 */
figure:has(img) { border-radius: 8px; overflow: hidden; }

/* 含有 :invalid 输入框的 form 高亮边框 */
form:has(input:invalid) {
  border-color: red;
}

/* 表格列悬停效果(JS 无法做到的 CSS 魔法)*/
td:has(+ td:hover) { background: lightyellow; }

六、伪类与伪元素

常用伪类

伪类 触发条件 常见用途
:hover 鼠标悬停 按钮/链接交互状态
:focus 键盘/点击获得焦点 表单元素焦点样式
:focus-visible 键盘导航获焦(推荐) 仅对键盘用户显示焦点轮廓
:active 鼠标按下期间 按钮点击反馈
:visited 已访问的链接 链接颜色区分
:checked checkbox/radio 被选中 自定义表单样式
:disabled 表单元素被禁用 禁用状态样式
:valid / :invalid 表单验证状态 实时校验视觉反馈
:placeholder-shown placeholder 可见时 浮动 label 效果
:empty 没有子元素(含文本) 隐藏空容器
:is() / :where() 参数中任意匹配 简化复杂选择器
:has() 包含指定后代 父选择器逻辑

结构性伪类(nth 系列)

li:first-child        { /* 第一个子元素 */ }
li:last-child         { /* 最后一个 */ }
li:only-child         { /* 唯一子元素 */ }
li:nth-child(2)        { /* 第 2 个 */ }
li:nth-child(odd)      { /* 奇数行 */ }
li:nth-child(even)     { /* 偶数行(斑马纹)*/ }
li:nth-child(3n+1)     { /* 1, 4, 7, 10… 每 3 个选第 1 个 */ }
li:nth-last-child(2)   { /* 从末尾数第 2 个 */ }

/* ⭐ :nth-child of type — CSS 2023+ */
li:nth-child(2 of .selected) {
  /* 第 2 个含 .selected 类的 li */
}

伪元素(使用双冒号 ::)

/* ::before / ::after — 内容前后插入虚拟元素 */
.icon::before {
  content: '🔥';      /* content 必须设置,哪怕为空 '' */
  display: inline-block;
}

/* ::first-line — 首行文字 */
p::first-line  { font-weight: bold; }

/* ::first-letter — 首字母(下沉效果)*/
p::first-letter {
  float: left;
  font-size: 3em;
  line-height: 1;
  margin-right: 0.1em;
}

/* ::selection — 用户选中的文字 */
::selection  { background: #ffd700; color: #000; }

/* ::placeholder — input 占位符 */
input::placeholder  { color: #aaa; font-style: italic; }

/* ::marker — li 的项目符号 */
li::marker  { color: tomato; font-size: 1.2em; }

/* ::backdrop — 全屏/dialog 背景遮罩 */
dialog::backdrop  { background: rgba(0,0,0,.5); }

七、CSS 盒模型(Box Model)

每个 HTML 元素都被视为一个矩形盒子,由四个区域从外到内组成:

┌─────────────────────────────────────┐
│              Margin(外边距)          │
│  ┌───────────────────────────────┐  │
│  │          Border(边框)         │  │
│  │  ┌─────────────────────────┐  │  │
│  │  │      Padding(内边距)    │  │  │
│  │  │  ┌───────────────────┐  │  │  │
│  │  │  │  Content(内容区)  │  │  │  │
│  │  │  └───────────────────┘  │  │  │
│  │  └─────────────────────────┘  │  │
│  └───────────────────────────────┘  │
└─────────────────────────────────────┘

box-sizing 对比

/* 默认:content-box — width 仅指内容区 */
.box {
  box-sizing: content-box;   /* 实际占宽 = width + padding + border */
  width: 200px;
  padding: 20px;
  border: 2px solid black;  /* 总宽 = 244px */
}

/* 推荐:border-box — width 包含 padding 和 border */
.box {
  box-sizing: border-box;    /* 实际占宽 = width = 200px */
  width: 200px;
  padding: 20px;
  border: 2px solid black;  /* 内容区 = 200 - 40 - 4 = 156px */
}

/* 全局最佳实践 */
*, *::before, *::after {
  box-sizing: border-box;
}

Margin 折叠

⚠️ 外边距折叠(Margin Collapse): 垂直方向相邻的 margin 会发生折叠,取两者中较大值而非相加。
折叠发生条件:① 相邻兄弟元素 ② 父子元素(父无 border/padding/BFC 时)③ 空元素(自身 margin-top 和 margin-bottom)。
BFC、Flex/Grid 容器内部不会发生折叠。


八、Display 与定位(Position)

display 属性

特性 典型元素
block 独占一行,可设宽高 div, p, h1-h6
inline 不换行,不可设宽高 span, a, em
inline-block 不换行,可设宽高 button, img
none 隐藏,不占空间
flex 弹性容器 详见 Flexbox 章节
grid 网格容器 详见 Grid 章节
contents 元素本身不渲染盒子,子元素正常显示 辅助无障碍场景
table 系列 模拟表格布局 table / table-cell 等

position 定位

/* static — 默认,不偏移,top/left 无效 */
.box { position: static; }

/* relative — 相对自身原位置偏移,不脱流 */
.box {
  position: relative;
  top: 10px; left: 20px;   /* 原位置占位保留 */
}

/* absolute — 相对最近的 positioned 祖先定位,脱流 */
.popup {
  position: absolute;
  top: 0; right: 0;         /* 找最近的 relative/absolute/fixed 父 */
}

/* fixed — 相对视口定位,滚动不移动 */
.navbar {
  position: fixed;
  top: 0; left: 0; right: 0;
}

/* sticky — 滚动到阈值前是 relative,之后是 fixed */
.section-header {
  position: sticky;
  top: 60px;   /* 距视口顶部 60px 时"吸附" */
}

/* z-index — 控制层叠顺序(仅对非 static 有效)*/
.modal { position: fixed; z-index: 1000; }

九、Flexbox 弹性布局

Flexbox 是一维布局模型,擅长在行或列方向上分配空间、对齐元素。

容器属性(父元素 display: flex)

.container {
  display: flex;                    /* 或 inline-flex */

  /* 主轴方向 */
  flex-direction: row;             /* row | row-reverse | column | column-reverse */

  /* 换行 */
  flex-wrap: wrap;                 /* nowrap | wrap | wrap-reverse */

  /* flex-flow 简写 */
  flex-flow: row wrap;

  /* 主轴对齐(水平,当 direction=row)*/
  justify-content: flex-start;    /* flex-start|flex-end|center|space-between|space-around|space-evenly */

  /* 交叉轴对齐(垂直)*/
  align-items: stretch;           /* stretch|flex-start|flex-end|center|baseline */

  /* 多行交叉轴对齐(wrap 时有效)*/
  align-content: flex-start;

  /* 子项间距 */
  gap: 16px;
  row-gap: 12px;
  column-gap: 24px;
}

子项属性(Flex Item)

.item {
  /* flex-grow: 剩余空间分配比例(0=不扩张)*/
  flex-grow: 1;

  /* flex-shrink: 空间不足时收缩比例(0=不收缩)*/
  flex-shrink: 1;

  /* flex-basis: 初始尺寸,优先级高于 width */
  flex-basis: 200px;

  /* flex 简写 = grow shrink basis */
  flex: 1 1 auto;   /* flex: 1 等于 1 1 0% */
  flex: none;        /* 0 0 auto — 不伸缩 */

  /* align-self: 覆盖容器的 align-items */
  align-self: center;

  /* order: 显示顺序(默认 0,越小越前)*/
  order: -1;
}

/* 经典垂直居中 */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}

十、CSS Grid 网格布局

Grid 是二维布局模型,同时控制行和列,适合复杂页面级布局。

.grid {
  display: grid;

  /* 定义列:3列,各占 1 份 */
  grid-template-columns: 1fr 1fr 1fr;

  /* 定义列:repeat + minmax — 响应式神器 */
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));

  /* 显式行高 */
  grid-template-rows: 80px auto 60px;

  /* 命名区域布局 */
  grid-template-areas:
    "header header header"
    "sidebar main   main"
    "footer footer footer";

  /* 间距 */
  gap: 20px 16px;   /* row-gap column-gap */

  /* 对齐 */
  justify-items: stretch;   /* 子项在列轴对齐 */
  align-items: stretch;     /* 子项在行轴对齐 */
  place-items: center;      /* align + justify 简写 */
}

/* Grid Item 属性 */
.header {
  grid-area: header;         /* 引用命名区域 */
}

.banner {
  /* 跨列:从第 1 条线到第 3 条线(占 2 列)*/
  grid-column: 1 / 3;
  grid-column: 1 / span 2;   /* 等价写法 */
  grid-row: 1 / 3;
}

/* 隐式网格控制 */
.grid {
  grid-auto-rows: minmax(100px, auto);
  grid-auto-flow: dense;   /* 自动填充空洞 */
}

💡 Flexbox vs Grid 选择原则:

  • Flexbox:一维排列(导航栏、卡片行、对齐按钮组)
  • Grid:二维布局(页面骨架、图片墙、仪表盘)
  • 两者可以嵌套使用:Grid 构建大布局,Flex 处理组件内部对齐。

十一、字体与文本

body {
  /* 字体栈:优先使用第一个,逐级回退 */
  font-family: 'Noto Sans SC', '微软雅黑', sans-serif;

  font-size: 16px;          /* 基准字号 */
  font-weight: 400;          /* 100-900,400=normal,700=bold */
  font-style: normal;        /* normal | italic | oblique */
  line-height: 1.6;          /* 行高,推荐无单位(相对于字号)*/
  letter-spacing: 0.02em;   /* 字符间距 */
  word-spacing: 0.1em;      /* 单词间距 */

  /* font 简写 */
  font: italic bold 16px/1.6 'Noto Sans SC', sans-serif;
}

p {
  text-align: left;           /* left|right|center|justify */
  text-indent: 2em;           /* 首行缩进 */
  text-decoration: none;      /* underline|line-through|overline */
  text-transform: uppercase;  /* uppercase|lowercase|capitalize */
  white-space: nowrap;        /* 禁止换行 */

  /* 单行溢出省略号 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  /* 多行省略(CSS 2023 正式标准)*/
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* ⭐ text-wrap: balance — 标题换行均衡(2023+)*/
h1, h2, h3 {
  text-wrap: balance;   /* 每行字数尽量均匀,避免孤行 */
}

/* Web 字体加载 */
@font-face {
  font-family: 'MyFont';
  src: url('font.woff2') format('woff2');
  font-display: swap;     /* 防止 FOIT:先显示备用字体 */
  font-weight: 100 900;   /* 可变字体范围 */
}

十二、颜色与背景

颜色表示方式

.colors {
  /* 关键字 */
  color: tomato;
  color: transparent;
  color: currentColor;   /* 继承当前 color 值 */

  /* HEX */
  color: #ff6347;         /* RGB */
  color: #ff634780;       /* RGBA(最后2位为透明度)*/

  /* RGB */
  color: rgb(255 99 71);         /* 现代无逗号语法 */
  color: rgb(255 99 71 / 0.5);   /* 50% 透明度 */

  /* HSL(更直观)*/
  color: hsl(9 100% 64%);
  color: hsl(9 100% 64% / 0.8);

  /* ⭐ OKLCH — 感知均匀颜色空间(2024+ 推荐)*/
  color: oklch(65% 0.2 30);  /* 亮度 色度 色相 */

  /* ⭐ 相对颜色语法(CSS 2024+ 全浏览器)*/
  color: oklch(from var(--brand) calc(l + 0.1) c h);

  /* ⭐ light-dark() — 自动适应深色/浅色模式 */
  color: light-dark(#000, #fff);
}

背景属性

.box {
  background-color: #f0f0f0;
  background-image: url('bg.jpg');
  background-repeat: no-repeat;    /* repeat|repeat-x|repeat-y|no-repeat */
  background-size: cover;          /* cover|contain|100% auto */
  background-position: center;     /* center|top left|50% 50% */
  background-attachment: fixed;    /* scroll|fixed|local */
  background-origin: border-box;
  background-clip: text;           /* 渐变文字效果 */

  /* 渐变背景 */
  background: linear-gradient(135deg, #667eea, #764ba2);
  background: radial-gradient(circle at center, #fff, #000);
  background: conic-gradient(from 0deg, red, yellow, green);

  /* 多背景叠加 */
  background:
    url('icon.svg') top right no-repeat,
    linear-gradient(#f5f5f5, #fff);
}

/* 渐变文字 */
.gradient-text {
  background: linear-gradient(90deg, #f093fb, #f5576c);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

十三、变换(Transform)与过渡(Transition)

transform 变换函数

.el {
  /* 位移 */
  transform: translateX(20px);
  transform: translate(20px, -10px);

  /* 缩放 */
  transform: scale(1.2);           /* 等比放大 1.2 倍 */
  transform: scaleX(2) scaleY(0.5);

  /* 旋转 */
  transform: rotate(45deg);
  transform: rotateX(60deg);       /* 3D 旋转 */

  /* 倾斜 */
  transform: skew(20deg, 5deg);

  /* 组合变换(从右到左执行)*/
  transform: translateY(-50%) rotate(30deg) scale(1.1);

  /* 变换原点 */
  transform-origin: top left;     /* 默认 center */

  /* 3D 透视 */
  perspective: 800px;
  transform-style: preserve-3d;
}

transition 过渡

.btn {
  background: #3b82f6;
  transform: scale(1);

  /* transition: property duration timing-function delay */
  transition: background .3s ease,
              transform  .2s cubic-bezier(0.34,1.56,0.64,1);
}

.btn:hover {
  background: #2563eb;
  transform: scale(1.05);
}

/*
  timing functions:
  ease | linear | ease-in | ease-out | ease-in-out
  cubic-bezier(x1,y1,x2,y2)
  steps(4, end) — 分步动画(如精灵图动画)
*/

/* ⭐ CSS 2024: transition-behavior — 支持 display 过渡 */
.modal {
  transition: opacity .3s, display .3s;
  transition-behavior: allow-discrete;
}

十四、CSS 动画(Animation)

/* ① 定义关键帧 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0%, 100%  { transform: scale(1); }
  50%        { transform: scale(1.1); }
}

/* ② 应用动画 */
.card {
  /* animation: name duration timing-function delay iteration-count direction fill-mode */
  animation: slideIn .5s ease-out both;

  /* 多动画叠加 */
  animation: slideIn .5s ease-out, pulse 2s ease-in-out infinite;
}

/* ③ 各属性详解 */
.el {
  animation-name: slideIn;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-delay: 0.2s;
  animation-iteration-count: infinite;  /* 数字或 infinite */
  animation-direction: alternate;       /* normal|reverse|alternate|alternate-reverse */
  animation-fill-mode: both;            /* none|forwards|backwards|both */
  animation-play-state: paused;         /* 暂停/运行 */
}

/* ⭐ 无障碍:尊重用户减少动画的系统偏好 */
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

/* ⭐ scroll-driven animations — 滚动驱动动画(CSS 2024+)*/
@keyframes reveal {
  from { opacity: 0; translate: 0 40px; }
  to   { opacity: 1; translate: 0 0; }
}

.card {
  animation: reveal linear both;
  animation-timeline: view();   /* 进入视口时触发 */
  animation-range: entry 0% entry 30%;
}

十五、CSS 自定义属性(变量)

CSS 自定义属性(Custom Properties)是原生变量系统,比预处理器变量更强大,支持运行时修改、作用域继承。

/* ① 定义:在 :root 上定义全局变量 */
:root {
  --color-primary: #3b82f6;
  --color-text: #1a1a1a;
  --spacing-md: 16px;
  --radius: 8px;
  --font-heading: 'Playfair Display', serif;
}

/* ② 使用:var(--name, fallback) */
.btn {
  background: var(--color-primary);
  padding: var(--spacing-md);
  border-radius: var(--radius, 4px);   /* 4px 为回退值 */
}

/* ③ 局部作用域:在组件内覆盖 */
.card-danger {
  --color-primary: #ef4444;    /* 仅在此元素及子元素有效 */
}

/* ④ 主题切换 */
[data-theme="dark"] {
  --color-text: #f0f0f0;
  --color-bg: #1a1a1a;
}

/* ⑤ 用于 calc() 计算 */
:root {
  --base-size: 16;   /* 无单位 */
}
.el {
  font-size: calc(var(--base-size) * 1px);
}

/* ⑥ JavaScript 读写 */
/*
  读取:getComputedStyle(el).getPropertyValue('--color-primary')
  写入:el.style.setProperty('--color-primary', '#ff0000')
*/

/* ⭐ @property — 注册类型化变量(CSS 2024+)*/
@property --progress {
  syntax: '<number>';
  initial-value: 0;
  inherits: false;
}
/* 类型化变量可以被 transition/animation 插值! */

十六、响应式设计

媒体查询(Media Queries)

/* 断点:移动优先(推荐)*/
/* 基础样式针对移动端,然后用 min-width 向上扩展 */

@media (min-width: 640px)  { /* sm: 平板竖屏 */ }
@media (min-width: 768px)  { /* md: 平板横屏 */ }
@media (min-width: 1024px) { /* lg: 桌面 */ }
@media (min-width: 1280px) { /* xl: 宽屏 */ }

/* 组合条件 */
@media (min-width: 768px) and (max-width: 1023px) { }

/* 媒体类型 */
@media print  { /* 打印样式 */ }
@media screen { /* 屏幕 */    }

/* 用户偏好媒体特性 */
@media (prefers-color-scheme: dark)   { /* 系统深色模式 */ }
@media (prefers-reduced-motion: reduce) { /* 减少动画 */ }
@media (prefers-contrast: high)        { /* 高对比度模式 */ }
@media (hover: none)                   { /* 触摸设备,无 hover */ }

/* ⭐ 范围媒体查询语法(CSS 2023+,更直观)*/
@media (768px <= width <= 1024px)  { }

容器查询(Container Queries)— CSS 2023+

/* ① 声明容器 */
.card-wrapper {
  container-type: inline-size;   /* 响应宽度变化 */
  container-name: card;          /* 命名(可选)*/
}

/* ② 在容器内部查询 */
@container (min-width: 400px) {
  .card {
    display: flex;
    gap: 16px;
  }
}

/* ③ 容器查询单位 */
.card-title {
  font-size: clamp(1rem, 3cqi, 2rem);
  /* cqi = container inline 的 1%(类似 vw,但基于容器)*/
}

响应式单位与函数

/* 视口单位 */
.hero {
  height: 100vh;    /* 视口高度 */
  width: 50vw;      /* 视口宽度 */
  font-size: 5vmin; /* vmin = min(vw, vh) */

  /* ⭐ 动态视口单位(解决移动端地址栏问题)*/
  height: 100svh;   /* small viewport height */
  height: 100lvh;   /* large viewport height */
  height: 100dvh;   /* dynamic viewport height(推荐)*/
}

/* 相对字体单位 */
.text {
  font-size: 1rem;   /* 相对于根元素字号 */
  padding: 1em;      /* 相对于当前元素字号 */
  width: 60ch;       /* 约 60 个字符宽,文章理想宽度 */
}

/* clamp() — 流体字体尺寸 */
h1 {
  /* 最小1.5rem,最大3rem,中间随视口线性变化 */
  font-size: clamp(1.5rem, 4vw + 0.5rem, 3rem);
}

/* min() max() */
.container {
  width: min(100%, 1200px);   /* 取较小值,等于 max-width */
  padding: max(16px, 4vw);    /* 取较大值 */
}

十七、现代 CSS 特性(2023–2025)

① CSS Nesting — 原生嵌套(无需 Sass)

.card {
  padding: 16px;

  & h2 { font-size: 1.5rem; }     /* .card h2 */
  &:hover { box-shadow: 0 4px 16px #0002; }

  @media (min-width: 768px) {
    display: flex;  /* 嵌套 @media */
  }
}

② @scope — 样式作用域

@scope (.card) to (.card__footer) {
  p { color: navy; }  /* 仅影响 .card 内、.card__footer 之前的 p */
}

③ @starting-style — 入场动画(2024+)

.popover {
  transition: opacity .3s, transform .3s, display .3s;
  transition-behavior: allow-discrete;
  opacity: 1;
  transform: translateY(0);
}

@starting-style {
  .popover {
    opacity: 0;
    transform: translateY(-10px);
  }
}

④ View Transitions — 页面转场动画

@view-transition {
  navigation: auto;
}

::view-transition-old(root) {
  animation: fadeOut .3s ease-in;
}

⑤ Anchor Positioning — 锚点定位(Chrome 2024+)

.tooltip {
  position-anchor: --btn;
  top: anchor(bottom);
  left: anchor(center);
}

⑥ text-wrap 新值

h1 { text-wrap: balance; }  /* 均匀分配每行字数 */
p  { text-wrap: pretty;  }  /* 避免段落最后一行孤字 */

⑦ Scrollbar 样式

.scroll {
  scrollbar-color: #888 #f0f0f0;  /* thumb track */
  scrollbar-width: thin;
  scrollbar-gutter: stable;        /* 预留滚动条空间防止布局跳动 */
}

⑧ content-visibility — 性能优化

.long-list-item {
  content-visibility: auto;         /* 跳过屏幕外元素的渲染 */
  contain-intrinsic-size: 0 200px;  /* 告知浏览器占位高度 */
}

新特性速览表

特性 说明 浏览器支持
:has() 父选择器 全浏览器(2023+)
@layer 层叠层管理 全浏览器(2022+)
@container 容器查询 全浏览器(2023+)
CSS Nesting 原生嵌套 全浏览器(2023+)
@scope 样式作用域 Chrome/Safari(2024+)
@starting-style 入场动画 Chrome/Firefox(2024+)
text-wrap: balance 标题均衡换行 全浏览器(2023+)
scrollbar-color 滚动条样式 全浏览器(2024+)
light-dark() 自动深浅色 全浏览器(2024+)
oklch() 颜色 感知均匀色彩 全浏览器(2023+)
滚动驱动动画 基于滚动的动画 Chrome(2023+)
锚点定位 CSS 定位工具 Chrome(2024+)

十八、CSS 最佳实践

性能优化

  • 将关键 CSS(Critical CSS)内联到 <head> 中,消除渲染阻塞
  • 使用 will-change: transform 提示浏览器提前创建合成层,但勿滥用
  • 动画优先使用 transformopacity(不触发重排/重绘,由 GPU 合成)
  • 使用 content-visibility: auto 跳过屏幕外元素渲染
  • 避免在频繁触发的事件(scroll、resize)中读取触发重排的属性

BEM 命名规范

/* BEM: Block__Element--Modifier */
.card                    { /* Block 块 */ }
.card__title             { /* Element 元素(双下划线)*/ }
.card__image             { /* Element */ }
.card--featured          { /* Modifier 修饰符(双连字符)*/ }
.card--featured .card__title { /* 修饰符影响子元素 */ }

/* 实用类(Utility Classes)配合使用 */
.mt-4   { margin-top: 1rem; }
.flex   { display: flex; }
.sr-only {           /* 仅供屏幕阅读器 */
  position: absolute;
  width: 1px; height: 1px;
  overflow: hidden;
  clip: rect(0,0,0,0);
  white-space: nowrap;
}

@layer 现代架构分层

/* 使用 @layer 明确定义层级顺序 */
@layer
  reset,       /* 浏览器默认样式重置 */
  tokens,      /* 设计令牌(CSS 变量)*/
  base,        /* 全局基础样式 */
  layout,      /* 页面骨架布局 */
  components,  /* 可复用 UI 组件 */
  patterns,    /* 组合模式 */
  utilities;   /* 单一功能类(最高优先级)*/

核心检查清单

  • ✅ 全局设置 box-sizing: border-box,避免 !important 滥用
  • ✅ 动画用 transform/opacity,不用 top/left/width
  • ✅ 媒体查询采用移动优先(min-width)策略
  • ✅ 图片设置 max-width: 100% 防溢出,文字用 rem 单位
  • ✅ 注意 :focus-visible 键盘焦点样式,颜色对比度 ≥ 4.5:1
  • ✅ 使用 CSS 变量统一管理设计令牌,用 @layer 管理优先级
  • ✅ 为 prefers-reduced-motion 提供无动画回退
  • ✅ 生产环境压缩 CSS,移除未使用的选择器(PurgeCSS)

推荐工具与资源

工具/资源 用途
MDN Web Docs 最权威的 CSS 属性文档与浏览器兼容性查询
Can I Use 查询 CSS 特性浏览器支持度
CSS-Tricks 深度教程与实践技巧
Autoprefixer 自动添加浏览器前缀
PostCSS CSS 转换工具链(类比 Babel for JS)
Sass / Less CSS 预处理器(原生嵌套普及后逐渐简化)
PurgeCSS 移除未使用的 CSS 选择器
Stylelint CSS 代码规范检查
State of CSS 年度 CSS 开发者调查报告(stateofcss.com)
web.dev / Chrome Developers Google 出品的现代 CSS 最新特性文章
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐