引言:
CSS 编程是使用 CSS 变量、数学函数、条件逻辑、模块化作用域等特性构建复杂样式系统的工程化方法论。本文完整系统地讲解 CSS 自定义属性、calc/min/clamp 等运算函数、@media/@supports/@container 条件查询、@layer/@scope 模块化机制、设计系统与主题构建、CSS 与 JavaScript 协同,以及嵌套、:has()、视图过渡等最新演进特性,涵盖 CSS 从基础到工程化的完整知识体系。

CSS 编程:从样式表到真正的“工程化”

当我们谈论“CSS 编程”时,我们并不是在说 CSS 是一门像 JavaScript 那样的通用编程语言。CSS 本质上是一种声明式语言——你告诉浏览器“元素应该长什么样”,而不是“如何一步步计算出来”。

但是,随着 Web 应用变得越来越复杂,CSS 也在不断进化,获得了很多传统意义上属于“编程语言”的特性:变量、逻辑判断、数学计算、函数、作用域、模块化……这些能力让 CSS 从简单的“样式描述”变成了可以构建复杂设计系统的“工程化工具”。

本文将完整、系统地讲解 CSS 编程的方方面面,涵盖 CSS 变量、运算与函数、条件逻辑、模块化作用域、设计系统、主题切换、CSS 与 JavaScript 协同,以及 CSS 的最新演进特性。

引言:CSS 是编程语言吗?

这个问题在开发者社区一直有争议。我们可以从几个维度来看:

支持“CSS 是编程语言”的观点:

  • 它有语法规则和语义。
  • 它有计算能力(通过 calc()、min()、max() 等函数)。
  • 它有变量(CSS 自定义属性)。
  • 它有条件逻辑(通过 @media、@supports 查询)。
  • 它有函数(颜色函数、数学函数、自定义函数等)。

反对观点:

  • 没有循环和迭代结构。
  • 无法定义算法或程序流程。
  • 不能处理输入/输出(除了修改样式)。
  • 缺少抽象数据类型。

结论:CSS 不是一种通用编程语言,但它是一种特定领域的编程语言(DSL,Domain Specific Language)。它的“编程”体现在:用声明式的方式描述视觉逻辑,用工程化的手段管理复杂样式系统。

第一章:CSS 变量——样式表的“存储引擎”

变量是任何编程语言的基石。CSS 自定义属性(CSS Variables)让样式表拥有了真正的“存储与复用”能力。

1.1 变量的声明与使用

声明一个自定义属性,需要使用以两个连字符 -- 开头的名称,并像普通属性一样赋予它一个值。

1
/* 在 :root 中声明全局变量 */
2
:root {
3
    --primary-color: #3498db;
4
    --secondary-color: #2ecc71;
5
    --spacing-unit: 8px;
6
    --border-radius: 4px;
7
    --font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
8
    --transition-duration: 0.3s;
9
    --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
10
}

使用变量时,通过 var() 函数来引用它。var() 函数接受一个变量名作为必要参数,并可以接受一个可选的“回退值”,当变量未定义时使用。

1
.button {
2
    background-color: var(--primary-color);
3
    padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 4);
4
    border-radius: var(--border-radius);
5
    font-family: var(--font-family);
6
    transition: all var(--transition-duration) ease;
7
    box-shadow: var(--shadow);
8
}
9
10
/* 带回退值的用法 */
11
.button-secondary {
12
    background-color: var(--secondary-color, #2ecc71);
13
    /* 如果 --secondary-color 未定义,则使用 #2ecc71 作为回退 */
14
}

1.2 变量的作用域与继承

自定义属性遵循 CSS 的层叠和继承规则。这意味着你可以为不同的元素或类分别定义相同的变量名,从而实现局部覆盖。

1
/* 全局作用域 */
2
:root {
3
    --bg-color: #ffffff;
4
    --text-color: #333333;
5
    --card-bg: #f5f5f5;
6
}
7
8
/* 深色主题容器内覆盖变量 */
9
.dark-theme {
10
    --bg-color: #1a1a1a;
11
    --text-color: #f0f0f0;
12
    --card-bg: #2d2d2d;
13
}
14
15
/* 卡片组件内再次覆盖 */
16
.card {
17
    --card-bg: #ffffff;
18
    background: var(--card-bg);
19
    color: var(--text-color);
20
}
21
22
/* 深色主题下的卡片 */
23
.dark-theme .card {
24
    --card-bg: #2d2d2d;
25
    /* 继承自 .dark-theme 的 --text-color */
26
}
27
28
body {
29
    background: var(--bg-color);
30
    color: var(--text-color);
31
}

1.3 JavaScript 操作 CSS 变量

CSS 变量是 CSS 和 JavaScript 之间的“桥梁”——JavaScript 可以读写 CSS 变量,实现动态样式控制。

1
// 读取 CSS 变量
2
const root = document.documentElement;
3
const primaryColor = getComputedStyle(root)
4
    .getPropertyValue('--primary-color').trim();
5
console.log(primaryColor); // "#3498db"
6
7
// 修改 CSS 变量(动态主题切换)
8
function setTheme(color) {
9
    document.documentElement.style.setProperty('--primary-color', color);
10
}
11
12
// 根据用户输入动态调整
13
const colorPicker = document.querySelector('#color-picker');
14
colorPicker.addEventListener('input', (e) => {
15
    document.documentElement.style.setProperty('--primary-color', e.target.value);
16
});
17
18
// 批量修改变量
19
function applyTheme(theme) {
20
    const root = document.documentElement;
21
    Object.entries(theme).forEach(([key, value]) => {
22
        root.style.setProperty(`--${key}`, value);
23
    });
24
}
25
26
// 使用示例
27
const darkTheme = {
28
    'bg-color': '#1a1a1a',
29
    'text-color': '#f0f0f0',
30
    'card-bg': '#2d2d2d'
31
};
32
applyTheme(darkTheme);

1.4 CSS 变量的高级用法

在 CSS 变量中存储复杂值:

1
:root {
2
    /* 存储颜色组合 */
3
    --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
4
    --gradient-secondary: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
5
    
6
    /* 存储滤镜 */
7
    --blur-filter: blur(8px);
8
    --brightness-filter: brightness(1.2);
9
    
10
    /* 存储变换 */
11
    --card-transform: rotate(2deg) scale(1.02);
12
}
13
14
.hero {
15
    background: var(--gradient-primary);
16
}
17
18
.modal-backdrop {
19
    filter: var(--blur-filter);
20
}
21
22
.card:hover {
23
    transform: var(--card-transform);
24
}

变量与 calc() 结合:

1
:root {
2
    --header-height: 60px;
3
    --footer-height: 80px;
4
    --content-min-height: calc(100vh - var(--header-height) - var(--footer-height));
5
}
6
7
.main-content {
8
    min-height: var(--content-min-height);
9
}
10
11
/* 响应式变量 */
12
:root {
13
    --container-padding: 16px;
14
}
15
16
@media (min-width: 768px) {
17
    :root {
18
        --container-padding: 32px;
19
    }
20
}
21
22
@media (min-width: 1200px) {
23
    :root {
24
        --container-padding: 48px;
25
    }
26
}
27
28
.container {
29
    padding: 0 var(--container-padding);
30
}

第二章:CSS 运算与函数

CSS 提供了多种内置函数和运算能力,可以进行数值计算和颜色处理。

2.1 数学运算函数

calc():四则运算

calc() 允许你在 CSS 属性值中进行加、减、乘、除运算,可以混合使用不同单位。

1
/* 基础运算 */
2
.container {
3
    width: calc(100% - 40px);
4
    /* 百分比与像素混合计算 */
5
    margin: calc(10px + 2vw);
6
    /* 相对单位与绝对单位混合 */
7
    font-size: calc(1rem + 0.5vw);
8
    /* 复杂表达式 */
9
    padding: calc((var(--spacing) * 2) + 4px);
10
}
11
12
/* 居中定位 */
13
.centered {
14
    position: absolute;
15
    top: calc(50% - 50px);
16
    left: calc(50% - 50px);
17
    width: 100px;
18
    height: 100px;
19
}
20
21
/* 响应式间距 */
22
.grid {
23
    gap: calc(8px + (24 - 8) * ((100vw - 320px) / (1200 - 320)));
24
    /* 从 8px 到 24px 随视口宽度变化 */
25
}

min():取最小值

min() 函数从多个值中取最小值,非常适合设置响应式的最大尺寸。

1
/* 宽度不超过 1200px,但不会小于 300px */
2
.container {
3
    width: min(1200px, 90%);
4
    /* 在宽屏上为 1200px,在小屏上为视口的 90% */
5
}
6
7
/* 字体大小取较小的那个值 */
8
.heading {
9
    font-size: min(3rem, 6vw);
10
    /* 在移动设备上不会太大,在桌面上不会太小 */
11
}
12
13
/* 间距取较小值 */
14
.sidebar {
15
    padding: min(2rem, 4%);
16
}

max():取最大值

max() 函数从多个值中取最大值,适合设置响应式的最小尺寸。

1
/* 宽度至少为 300px,但不超过 100% */
2
.container {
3
    width: max(300px, 70%);
4
}
5
6
/* 字体至少为 1rem */
7
.text {
8
    font-size: max(1rem, 1.2vw);
9
}
10
11
/* 间距至少为 8px */
12
.element {
13
    padding: max(8px, 2%);
14
}

clamp():在最小值和最大值之间取值

clamp() 是 min() 和 max() 的结合,接受三个参数:最小值、首选值、最大值。它是响应式设计的利器。

1
/* 响应式字体:最小 1rem,理想值 2vw + 1rem,最大 2rem */
2
h1 {
3
    font-size: clamp(1.5rem, 4vw, 3rem);
4
    /* 在 375px 视口下约为 1.5rem,在 1200px 视口下约为 3rem */
5
}
6
7
/* 响应式容器宽度 */
8
.container {
9
    width: clamp(320px, 80%, 1200px);
10
    /* 最小 320px,最大 1200px,理想为 80% */
11
}
12
13
/* 响应式间距 */
14
.element {
15
    padding: clamp(0.5rem, 2vw, 2rem);
16
}
17
18
/* 响应式网格列数 */
19
.grid {
20
    grid-template-columns: repeat(auto-fit, minmax(clamp(150px, 25%, 300px), 1fr));
21
}

2.2 颜色函数

基础颜色函数:rgb()、rgba()、hsl()、hsla()

1
/* RGB 颜色 */
2
.element {
3
    color: rgb(52, 152, 219);
4
    background: rgba(52, 152, 219, 0.5);
5
}
6
7
/* HSL 颜色(色相、饱和度、亮度) */
8
.element {
9
    color: hsl(210, 80%, 50%);
10
    background: hsla(210, 80%, 50%, 0.5);
11
}
12
13
/* 使用 CSS 变量动态控制颜色 */
14
:root {
15
    --brand-hue: 210;
16
    --brand-saturation: 80%;
17
    --brand-lightness: 50%;
18
}
19
20
.button {
21
    background: hsl(var(--brand-hue), var(--brand-saturation), var(--brand-lightness));
22
}
23
24
.button:hover {
25
    background: hsl(var(--brand-hue), var(--brand-saturation), calc(var(--brand-lightness) - 10%));
26
}

color-mix():混合颜色(CSS Color Level 5)

color-mix() 允许在颜色空间中混合两种颜色,指定混合比例。

1
/* 基础混合 */
2
.button-primary {
3
    background: color-mix(in srgb, #3498db 70%, white);
4
    /* 70% #3498db + 30% white */
5
}
6
7
.button-primary-hover {
8
    background: color-mix(in srgb, #3498db 70%, black);
9
    /* 70% #3498db + 30% black,得到更暗的版本 */
10
}
11
12
/* 使用 CSS 变量 */
13
:root {
14
    --primary: #3498db;
15
}
16
.button {
17
    background: color-mix(in srgb, var(--primary) 80%, var(--secondary) 20%);
18
}
19
20
/* 不同颜色空间的混合 */
21
.element {
22
    /* 在 HSL 颜色空间中混合 */
23
    background: color-mix(in hsl, red 50%, blue);
24
    /* 在 OKLCH 颜色空间中混合(更精确) */
25
    border-color: color-mix(in oklch, #3498db 60%, #2ecc71);
26
}

color-contrast():选择最佳对比色

color-contrast() 函数从多个候选颜色中选出与基准颜色对比度最高的那个,用于确保可访问性。

1
/* 自动选择与背景对比度最高的文字颜色 */
2
.element {
3
    background: #3498db;
4
    color: color-contrast(#3498db vs white, black);
5
    /* 如果 #3498db 与 white 的对比度足够高,使用 white;否则使用 black */
6
}
7
8
/* 多个候选颜色 */
9
.element {
10
    background: #1a1a1a;
11
    color: color-contrast(#1a1a1a vs white, #f0f0f0, #cccccc);
12
    /* 选择与 #1a1a1a 对比度最高的颜色 */
13
}

其他颜色函数

1
/* 调整颜色的亮度 */
2
.element {
3
    background: hsl(from var(--primary) h s calc(l + 10%));
4
}
5
6
/* 相对颜色语法(从现有颜色创建新颜色) */
7
:root {
8
    --primary: #3498db;
9
    --primary-light: hsl(from var(--primary) h s calc(l + 20%));
10
    --primary-dark: hsl(from var(--primary) h s calc(l - 20%));
11
}
12
13
/* 颜色解析函数(将颜色字符串转换为 RGB 分量) */
14
/* 这通常需要 JavaScript 辅助,CSS 原生支持有限 */

2.3 其他常用函数

attr():获取 HTML 属性值

attr() 函数允许从 HTML 元素的属性中获取值并用于样式。

1
/* 基础用法:从 data 属性获取值 */
2
.element {
3
    content: attr(data-label);
4
    background-color: attr(data-color, #3498db);
5
    /* 如果 data-color 不存在,使用回退值 #3498db */
6
}
7
8
/* 结合 CSS 变量使用 */
9
.tooltip::after {
10
    content: attr(data-tooltip);
11
    position: absolute;
12
    background: #333;
13
    color: white;
14
    padding: 4px 8px;
15
    border-radius: 4px;
16
    font-size: 12px;
17
}
1
<!-- HTML 中的使用 -->
2
<div class="element" data-label="提示信息" data-color="#e74c3c">
3
    悬停查看提示
4
</div>

url():加载外部资源

1
/* 加载图片 */
2
.hero {
3
    background-image: url('/images/hero.jpg');
4
}
5
6
/* 动态图片(结合 CSS 变量) */
7
:root {
8
    --hero-image: url('/images/hero-default.jpg');
9
}
10
11
.hero {
12
    background-image: var(--hero-image);
13
}
14
15
/* 使用媒体查询切换图片 */
16
@media (min-resolution: 2dppx) {
17
    .hero {
18
        background-image: url('/images/hero@2x.jpg');
19
    }
20
}

var() 与自定义属性的组合使用

1
/* 复杂的变量组合 */
2
:root {
3
    --spacing-xs: 4px;
4
    --spacing-sm: 8px;
5
    --spacing-md: 16px;
6
    --spacing-lg: 24px;
7
    --spacing-xl: 32px;
8
    
9
    --spacing: var(--spacing-md);  /* 默认间距 */
10
}
11
12
.card {
13
    padding: var(--spacing);
14
    margin-bottom: var(--spacing-lg);
15
}
16
17
/* 在媒体查询中覆盖变量 */
18
@media (max-width: 768px) {
19
    :root {
20
        --spacing: var(--spacing-sm);
21
        --spacing-lg: var(--spacing-md);
22
    }
23
}

第三章:CSS 条件逻辑

CSS 中的条件逻辑主要通过 @media 查询、@supports 查询和 @container 查询 实现。

3.1 @media 媒体查询

媒体查询是 CSS 最基础的条件逻辑,根据设备特性应用不同的样式。

视口相关查询:

1
/* 根据视口宽度调整布局 */
2
.grid {
3
    display: grid;
4
    grid-template-columns: repeat(3, 1fr);
5
    gap: 20px;
6
}
7
8
/* 平板设备 */
9
@media (max-width: 1024px) {
10
    .grid {
11
        grid-template-columns: repeat(2, 1fr);
12
    }
13
}
14
15
/* 手机设备 */
16
@media (max-width: 768px) {
17
    .grid {
18
        grid-template-columns: 1fr;
19
    }
20
}
21
22
/* 组合条件:宽度在 768px 到 1024px 之间 */
23
@media (min-width: 768px) and (max-width: 1024px) {
24
    .sidebar {
25
        display: none;
26
    }
27
}
28
29
/* 高度相关的查询 */
30
@media (min-height: 800px) {
31
    .hero {
32
        min-height: 80vh;
33
    }
34
}

设备特性查询:

1
/* 暗色模式偏好 */
2
@media (prefers-color-scheme: dark) {
3
    :root {
4
        --bg: #1a1a1a;
5
        --text: #f0f0f0;
6
        --card-bg: #2d2d2d;
7
        --border-color: #404040;
8
    }
9
}
10
11
@media (prefers-color-scheme: light) {
12
    :root {
13
        --bg: #ffffff;
14
        --text: #222222;
15
        --card-bg: #f5f5f5;
16
        --border-color: #e0e0e0;
17
    }
18
}
19
20
/* 减少动画偏好(为运动敏感用户设计) */
21
@media (prefers-reduced-motion: reduce) {
22
    *,
23
    *::before,
24
    *::after {
25
        animation-duration: 0.01ms !important;
26
        animation-iteration-count: 1 !important;
27
        transition-duration: 0.01ms !important;
28
    }
29
}
30
31
/* 高对比度偏好 */
32
@media (prefers-contrast: high) {
33
    :root {
34
        --text: #000000;
35
        --bg: #ffffff;
36
        --border-color: #000000;
37
        --shadow: none;
38
    }
39
}
40
41
/* 系统主题色偏好 */
42
@media (prefers-color-scheme: dark) {
43
    .theme-toggle-icon {
44
        content: "🌙";
45
    }
46
}
47
48
@media (prefers-color-scheme: light) {
49
    .theme-toggle-icon {
50
        content: "☀️";
51
    }
52
}

设备类型查询:

1
/* 打印样式 */
2
@media print {
3
    .no-print {
4
        display: none !important;
5
    }
6
    body {
7
        background: white;
8
        color: black;
9
        font-size: 12pt;
10
    }
11
    a[href]::after {
12
        content: " (" attr(href) ")";
13
    }
14
}
15
16
/* 屏幕阅读器专用样式 */
17
@media speech {
18
    .sr-only {
19
        display: block;
20
    }
21
}
22
23
/* 触摸设备 */
24
@media (hover: none) and (pointer: coarse) {
25
    /* 触摸设备上的样式调整 */
26
    .button {
27
        min-height: 44px;
28
        min-width: 44px;
29
        padding: 12px 16px;
30
    }
31
}

3.2 @supports 特性检测

@supports 查询允许检测浏览器是否支持某个 CSS 特性,从而提供回退方案。

1
/* 检测 Grid 布局支持 */
2
@supports (display: grid) {
3
    .container {
4
        display: grid;
5
        grid-template-columns: 1fr 1fr 1fr;
6
        gap: 20px;
7
    }
8
}
9
10
@supports not (display: grid) {
11
    .container {
12
        display: flex;
13
        flex-wrap: wrap;
14
    }
15
    .container > * {
16
        flex: 1 1 33.333%;
17
        margin: 10px;
18
    }
19
}
20
21
/* 检测嵌套语法支持 */
22
@supports (selector(&)) {
23
    .card {
24
        &__title {
25
            font-size: 1.5rem;
26
        }
27
        &__body {
28
            padding: 1rem;
29
        }
30
    }
31
}
32
33
/* 检测容器查询支持 */
34
@supports (container-type: inline-size) {
35
    .card-container {
36
        container-type: inline-size;
37
    }
38
    
39
    @container (min-width: 400px) {
40
        .card {
41
            display: flex;
42
            flex-direction: row;
43
        }
44
    }
45
}
46
47
/* 检测子网格支持 */
48
@supports (grid-template-columns: subgrid) {
49
    .grid {
50
        display: grid;
51
        grid-template-columns: subgrid;
52
    }
53
}
54
55
/* 检测 has() 选择器支持 */
56
@supports (selector(:has(*))) {
57
    .container:has(.featured) {
58
        background: var(--highlight);
59
    }
60
}
61
62
/* 组合检测 */
63
@supports (display: grid) and (gap: 20px) {
64
    .grid {
65
        display: grid;
66
        gap: 20px;
67
    }
68
}

3.3 @container 容器查询

容器查询是 CSS 响应式设计的重大突破——它允许组件根据其容器的大小来调整样式,而不是视口大小。

1
/* 定义容器 */
2
.card-container {
3
    container-type: inline-size;
4
    container-name: card;
5
}
6
7
/* 或者简写 */
8
.card-wrapper {
9
    container: card / inline-size;
10
}
11
12
/* 根据容器宽度调整样式 */
13
@container card (min-width: 400px) {
14
    .card {
15
        display: flex;
16
        flex-direction: row;
17
        align-items: center;
18
    }
19
    
20
    .card-image {
21
        flex: 0 0 40%;
22
        margin-right: 20px;
23
    }
24
}
25
26
@container card (max-width: 399px) {
27
    .card {
28
        display: flex;
29
        flex-direction: column;
30
    }
31
    
32
    .card-image {
33
        margin-bottom: 16px;
34
    }
35
}
36
37
/* 容器高度查询 */
38
@container card (min-height: 300px) {
39
    .card-content {
40
        display: flex;
41
        flex-direction: column;
42
        justify-content: center;
43
    }
44
}
45
46
/* 容器尺寸区间查询 */
47
@container card (min-width: 400px) and (max-width: 800px) {
48
    .card {
49
        padding: 16px;
50
    }
51
}
52
53
/* 使用容器查询的响应式组件示例 */
54
.product-card {
55
    container: product / inline-size;
56
}
57
58
@container product (min-width: 300px) {
59
    .product-card {
60
        display: grid;
61
        grid-template-columns: 120px 1fr;
62
        gap: 16px;
63
    }
64
}
65
66
@container product (min-width: 500px) {
67
    .product-card {
68
        grid-template-columns: 200px 1fr;
69
        gap: 24px;
70
    }
71
    
72
    .product-title {
73
        font-size: 1.5rem;
74
    }
75
}

第四章:CSS 模块化与作用域

4.1 @layer 级联层

@layer 是 CSS 的一个相对较新的特性,用于控制样式规则在不同层级之间的优先级,而不需要依赖选择器权重或 !important。

1
/* 定义级联层的顺序(越靠后优先级越高) */
2
@layer reset, base, components, utilities, overrides;
3
4
/* 在特定层级中定义样式 */
5
@layer reset {
6
    * {
7
        margin: 0;
8
        padding: 0;
9
        box-sizing: border-box;
10
    }
11
    
12
    body {
13
        line-height: 1.5;
14
    }
15
}
16
17
@layer base {
18
    :root {
19
        --primary: #3498db;
20
        --text: #333;
21
    }
22
    
23
    body {
24
        font-family: 'Inter', sans-serif;
25
        color: var(--text);
26
        background: #fff;
27
    }
28
}
29
30
@layer components {
31
    .button {
32
        display: inline-block;
33
        padding: 8px 16px;
34
        background: var(--primary);
35
        color: white;
36
        border: none;
37
        border-radius: 4px;
38
        cursor: pointer;
39
    }
40
    
41
    .card {
42
        padding: 20px;
43
        background: white;
44
        border-radius: 8px;
45
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
46
    }
47
}
48
49
@layer utilities {
50
    .text-center {
51
        text-align: center;
52
    }
53
    
54
    .mt-1 {
55
        margin-top: 8px;
56
    }
57
    
58
    .mt-2 {
59
        margin-top: 16px;
60
    }
61
}
62
63
/* 嵌套 layer */
64
@layer framework {
65
    @layer components {
66
        .button {
67
            /* framework 的按钮样式 */
68
        }
69
    }
70
}
71
72
/* 导入外部样式并放入特定层 */
73
@import url('reset.css') layer(reset);
74
@import url('components.css') layer(components);

4.2 @scope 作用域

@scope 是一项较新的 CSS 特性,允许将样式限制在 DOM 树的特定范围内,从而避免样式泄漏。

1
/* 基础用法:样式只应用于 .card 内部的子元素 */
2
@scope (.card) {
3
    .title {
4
        font-size: 1.5rem;
5
        font-weight: bold;
6
        color: var(--text-primary);
7
    }
8
    
9
    .body {
10
        padding: 1rem;
11
        line-height: 1.6;
12
    }
13
    
14
    .footer {
15
        padding: 0.75rem 1rem;
16
        border-top: 1px solid var(--border);
17
        font-size: 0.875rem;
18
        color: var(--text-secondary);
19
    }
20
}
21
22
/* 带作用域限制:只应用于直接子元素 */
23
@scope (.card) to (.card-inner) {
24
    .title {
25
        /* 只作用于 .card 的直接子级,且不作用于 .card-inner 内部的 .title */
26
    }
27
}
28
29
/* 嵌套作用域 */
30
@scope (.sidebar) {
31
    .nav-item {
32
        padding: 8px 16px;
33
    }
34
    
35
    @scope (.nav-section) {
36
        .nav-item {
37
            padding-left: 32px;
38
            /* 更深的导航层级使用不同的缩进 */
39
        }
40
    }
41
}
42
43
/* 作用域与媒体查询结合 */
44
@scope (.card) {
45
    .title {
46
        font-size: 1.25rem;
47
    }
48
    
49
    @media (min-width: 768px) {
50
        .title {
51
            font-size: 1.75rem;
52
        }
53
    }
54
}

4.3 CSS 模块(构建工具层面)

CSS 模块是通过构建工具(如 Webpack、Vite)实现的样式作用域隔离,它会在构建时为每个类名生成唯一的哈希值。

1
/* styles.module.css */
2
.button {
3
    background: #3498db;
4
    color: white;
5
    padding: 8px 16px;
6
    border-radius: 4px;
7
}
8
9
.button-primary {
10
    background: #2ecc71;
11
}
12
13
.container {
14
    padding: 20px;
15
    max-width: 1200px;
16
    margin: 0 auto;
17
}
1
// 在 JavaScript 中导入
2
import styles from './styles.module.css';
3
4
// 使用样式
5
<div className={styles.container}>
6
    <button className={`${styles.button} ${styles.buttonPrimary}`}>
7
        点击我
8
    </button>
9
</div>

构建后,类名会被转换为类似 .button_abc123 的格式,确保样式不会污染全局。

4.4 CSS-in-JS(运行时作用域)

CSS-in-JS 是在 JavaScript 中定义样式的方案,天然具有作用域隔离。

1
// 使用 styled-components
2
import styled from 'styled-components';
3
4
const Button = styled.button`
5
    background: #3498db;
6
    color: white;
7
    padding: 8px 16px;
8
    border-radius: 4px;
9
    &:hover {
10
        background: #2980b9;
11
    }
12
`;
13
14
const PrimaryButton = styled(Button)`
15
    background: #2ecc71;
16
    &:hover {
17
        background: #27ae60;
18
    }
19
`;
20
21
// 使用
22
<Button>普通按钮</Button>
23
<PrimaryButton>主要按钮</PrimaryButton>
1
// 使用 Emotion
2
import { css } from '@emotion/react';
3
4
const buttonStyle = css`
5
    background: #3498db;
6
    color: white;
7
    padding: 8px 16px;
8
    border-radius: 4px;
9
`;
10
11
<button css={buttonStyle}>点击我</button>

第五章:设计系统与 CSS 编程

设计系统(Design System)是一套可复用的设计规范和组件库,而 CSS 变量是实现设计系统的最佳工具。

5.1 设计令牌(Design Tokens)

设计令牌是设计系统中最小、最基础的样式单元。

1
/* 基础设计令牌 */
2
:root {
3
    /* ===== 颜色系统 ===== */
4
    /* 品牌色 */
5
    --color-brand-50: #ebf5fb;
6
    --color-brand-100: #d6eaf8;
7
    --color-brand-200: #aed6f1;
8
    --color-brand-300: #85c1e9;
9
    --color-brand-400: #5dade2;
10
    --color-brand-500: #3498db;
11
    --color-brand-600: #2e86c1;
12
    --color-brand-700: #2874a6;
13
    --color-brand-800: #21618c;
14
    --color-brand-900: #1a5276;
15
    
16
    /* 中性色 */
17
    --color-neutral-50: #f8f9fa;
18
    --color-neutral-100: #f1f3f4;
19
    --color-neutral-200: #e9ecef;
20
    --color-neutral-300: #dee2e6;
21
    --color-neutral-400: #ced4da;
22
    --color-neutral-500: #adb5bd;
23
    --color-neutral-600: #6c757d;
24
    --color-neutral-700: #495057;
25
    --color-neutral-800: #343a40;
26
    --color-neutral-900: #212529;
27
    
28
    /* 语义色 */
29
    --color-success: #2ecc71;
30
    --color-warning: #f39c12;
31
    --color-danger: #e74c3c;
32
    --color-info: #3498db;
33
    
34
    /* ===== 字体系统 ===== */
35
    --font-family-base: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
36
    --font-family-heading: 'Poppins', 'Inter', sans-serif;
37
    --font-family-mono: 'JetBrains Mono', 'Fira Code', monospace;
38
    
39
    --font-size-xs: 0.75rem;    /* 12px */
40
    --font-size-sm: 0.875rem;   /* 14px */
41
    --font-size-base: 1rem;     /* 16px */
42
    --font-size-lg: 1.125rem;   /* 18px */
43
    --font-size-xl: 1.25rem;    /* 20px */
44
    --font-size-2xl: 1.5rem;    /* 24px */
45
    --font-size-3xl: 1.875rem;  /* 30px */
46
    --font-size-4xl: 2.25rem;   /* 36px */
47
    --font-size-5xl: 3rem;      /* 48px */
48
    
49
    --font-weight-normal: 400;
50
    --font-weight-medium: 500;
51
    --font-weight-semibold: 600;
52
    --font-weight-bold: 700;
53
    --font-weight-extrabold: 800;
54
    
55
    --line-height-tight: 1.25;
56
    --line-height-normal: 1.5;
57
    --line-height-loose: 1.75;
58
    
59
    /* ===== 间距系统 ===== */
60
    --space-0: 0;
61
    --space-1: 0.25rem;   /* 4px */
62
    --space-2: 0.5rem;    /* 8px */
63
    --space-3: 0.75rem;   /* 12px */
64
    --space-4: 1rem;      /* 16px */
65
    --space-5: 1.25rem;   /* 20px */
66
    --space-6: 1.5rem;    /* 24px */
67
    --space-7: 1.75rem;   /* 28px */
68
    --space-8: 2rem;      /* 32px */
69
    --space-9: 2.25rem;   /* 36px */
70
    --space-10: 2.5rem;   /* 40px */
71
    --space-11: 2.75rem;  /* 44px */
72
    --space-12: 3rem;     /* 48px */
73
    --space-14: 3.5rem;   /* 56px */
74
    --space-16: 4rem;     /* 64px */
75
    --space-20: 5rem;     /* 80px */
76
    --space-24: 6rem;     /* 96px */
77
    
78
    /* ===== 圆角系统 ===== */
79
    --radius-none: 0;
80
    --radius-sm: 0.125rem;  /* 2px */
81
    --radius-base: 0.25rem; /* 4px */
82
    --radius-md: 0.375rem;  /* 6px */
83
    --radius-lg: 0.5rem;    /* 8px */
84
    --radius-xl: 0.75rem;   /* 12px */
85
    --radius-2xl: 1rem;     /* 16px */
86
    --radius-3xl: 1.5rem;   /* 24px */
87
    --radius-full: 9999px;
88
    
89
    /* ===== 阴影系统 ===== */
90
    --shadow-xs: 0 1px 2px rgba(0, 0, 0, 0.05);
91
    --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.1), 0 1px 2px rgba(0, 0, 0, 0.06);
92
    --shadow-base: 0 4px 6px rgba(0, 0, 0, 0.07), 0 2px 4px rgba(0, 0, 0, 0.06);
93
    --shadow-md: 0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
94
    --shadow-lg: 0 20px 25px rgba(0, 0, 0, 0.1), 0 10px 10px rgba(0, 0, 0, 0.04);
95
    --shadow-xl: 0 25px 50px rgba(0, 0, 0, 0.15);
96
    --shadow-2xl: 0 50px 100px rgba(0, 0, 0, 0.2);
97
    
98
    /* ===== 过渡系统 ===== */
99
    --transition-fast: 0.15s ease;
100
    --transition-base: 0.3s ease;
101
    --transition-slow: 0.5s ease;
102
    --transition-slower: 0.8s ease;
103
    
104
    /* ===== 容器宽度 ===== */
105
    --container-sm: 640px;
106
    --container-md: 768px;
107
    --container-lg: 1024px;
108
    --container-xl: 1280px;
109
    --container-2xl: 1536px;
110
}

5.2 基于设计令牌的组件构建

1
/* 使用设计令牌构建组件 */
2
3
/* ===== 按钮组件 ===== */
4
.btn {
5
    display: inline-flex;
6
    align-items: center;
7
    justify-content: center;
8
    gap: var(--space-2);
9
    padding: var(--space-2) var(--space-5);
10
    font-family: var(--font-family-base);
11
    font-size: var(--font-size-base);
12
    font-weight: var(--font-weight-medium);
13
    line-height: var(--line-height-normal);
14
    text-decoration: none;
15
    border: 1px solid transparent;
16
    border-radius: var(--radius-md);
17
    cursor: pointer;
18
    transition: all var(--transition-fast);
19
    
20
    &:disabled {
21
        opacity: 0.6;
22
        cursor: not-allowed;
23
    }
24
}
25
26
/* 按钮变体 */
27
.btn-primary {
28
    background: var(--color-brand-500);
29
    color: white;
30
    
31
    &:hover:not(:disabled) {
32
        background: var(--color-brand-600);
33
    }
34
    
35
    &:active:not(:disabled) {
36
        background: var(--color-brand-700);
37
    }
38
}
39
40
.btn-secondary {
41
    background: var(--color-neutral-200);
42
    color: var(--color-neutral-800);
43
    
44
    &:hover:not(:disabled) {
45
        background: var(--color-neutral-300);
46
    }
47
}
48
49
.btn-success {
50
    background: var(--color-success);
51
    color: white;
52
    
53
    &:hover:not(:disabled) {
54
        filter: brightness(0.9);
55
    }
56
}
57
58
.btn-danger {
59
    background: var(--color-danger);
60
    color: white;
61
    
62
    &:hover:not(:disabled) {
63
        filter: brightness(0.9);
64
    }
65
}
66
67
/* 按钮尺寸 */
68
.btn-sm {
69
    padding: var(--space-1) var(--space-3);
70
    font-size: var(--font-size-sm);
71
}
72
73
.btn-lg {
74
    padding: var(--space-3) var(--space-7);
75
    font-size: var(--font-size-lg);
76
}
77
78
/* ===== 卡片组件 ===== */
79
.card {
80
    background: white;
81
    border-radius: var(--radius-lg);
82
    box-shadow: var(--shadow-base);
83
    overflow: hidden;
84
    transition: box-shadow var(--transition-base);
85
    
86
    &:hover {
87
        box-shadow: var(--shadow-lg);
88
    }
89
}
90
91
.card-header {
92
    padding: var(--space-5) var(--space-5) var(--space-3);
93
    border-bottom: 1px solid var(--color-neutral-200);
94
}
95
96
.card-title {
97
    font-family: var(--font-family-heading);
98
    font-size: var(--font-size-xl);
99
    font-weight: var(--font-weight-semibold);
100
    color: var(--color-neutral-900);
101
    margin: 0;
102
}
103
104
.card-body {
105
    padding: var(--space-5);
106
}
107
108
.card-footer {
109
    padding: var(--space-3) var(--space-5);
110
    background: var(--color-neutral-50);
111
    border-top: 1px solid var(--color-neutral-200);
112
}
113
114
/* ===== 输入框组件 ===== */
115
.input {
116
    display: block;
117
    width: 100%;
118
    padding: var(--space-2) var(--space-3);
119
    font-family: var(--font-family-base);
120
    font-size: var(--font-size-base);
121
    line-height: var(--line-height-normal);
122
    color: var(--color-neutral-800);
123
    background: white;
124
    border: 1px solid var(--color-neutral-300);
125
    border-radius: var(--radius-md);
126
    transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
127
    
128
    &:focus {
129
        outline: none;
130
        border-color: var(--color-brand-500);
131
        box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.15);
132
    }
133
    
134
    &::placeholder {
135
        color: var(--color-neutral-400);
136
    }
137
    
138
    &:disabled {
139
        background: var(--color-neutral-100);
140
        cursor: not-allowed;
141
    }
142
}

5.3 主题系统

1
/* ===== 主题系统 ===== */
2
3
/* 基础主题(浅色) */
4
:root,
5
[data-theme="light"] {
6
    --theme-bg: #ffffff;
7
    --theme-text: #212529;
8
    --theme-text-secondary: #6c757d;
9
    --theme-card-bg: #ffffff;
10
    --theme-card-border: #e9ecef;
11
    --theme-input-bg: #ffffff;
12
    --theme-input-border: #ced4da;
13
    --theme-hover: #f8f9fa;
14
    --theme-shadow: 0 4px 6px rgba(0, 0, 0, 0.07);
15
    --theme-shadow-lg: 0 20px 25px rgba(0, 0, 0, 0.1);
16
    --theme-scrollbar-track: #f1f3f4;
17
    --theme-scrollbar-thumb: #ced4da;
18
}
19
20
/* 暗色主题 */
21
[data-theme="dark"] {
22
    --theme-bg: #121212;
23
    --theme-text: #e4e4e4;
24
    --theme-text-secondary: #a0a0a0;
25
    --theme-card-bg: #1e1e1e;
26
    --theme-card-border: #333333;
27
    --theme-input-bg: #2d2d2d;
28
    --theme-input-border: #404040;
29
    --theme-hover: #2d2d2d;
30
    --theme-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
31
    --theme-shadow-lg: 0 20px 25px rgba(0, 0, 0, 0.4);
32
    --theme-scrollbar-track: #2d2d2d;
33
    --theme-scrollbar-thumb: #555555;
34
}
35
36
/* 高对比度主题 */
37
[data-theme="high-contrast"] {
38
    --theme-bg: #ffffff;
39
    --theme-text: #000000;
40
    --theme-text-secondary: #000000;
41
    --theme-card-bg: #ffffff;
42
    --theme-card-border: #000000;
43
    --theme-input-bg: #ffffff;
44
    --theme-input-border: #000000;
45
    --theme-hover: #f0f0f0;
46
    --theme-shadow: none;
47
    --theme-shadow-lg: none;
48
}
49
50
/* 使用主题变量的组件 */
51
body {
52
    background: var(--theme-bg);
53
    color: var(--theme-text);
54
    transition: background var(--transition-slow), color var(--transition-slow);
55
}
56
57
.card {
58
    background: var(--theme-card-bg);
59
    border: 1px solid var(--theme-card-border);
60
    box-shadow: var(--theme-shadow);
61
}
62
63
.input {
64
    background: var(--theme-input-bg);
65
    border-color: var(--theme-input-border);
66
    color: var(--theme-text);
67
}
68
69
/* 暗色模式下的滚动条 */
70
[data-theme="dark"] {
71
    scrollbar-color: var(--theme-scrollbar-thumb) var(--theme-scrollbar-track);
72
    scrollbar-width: thin;
73
}

第六章:CSS 与 JavaScript 的协同编程

6.1 通过 CSS 变量动态控制样式

1
// 完整的主题切换系统
2
class ThemeManager {
3
    constructor() {
4
        this.root = document.documentElement;
5
        this.currentTheme = this.loadTheme() || 'light';
6
        this.themes = {
7
            light: {
8
                'theme-bg': '#ffffff',
9
                'theme-text': '#212529',
10
                'theme-text-secondary': '#6c757d',
11
                'theme-card-bg': '#ffffff',
12
                'theme-card-border': '#e9ecef',
13
                'theme-input-bg': '#ffffff',
14
                'theme-input-border': '#ced4da',
15
                'theme-hover': '#f8f9fa',
16
                'theme-shadow': '0 4px 6px rgba(0,0,0,0.07)',
17
                'theme-shadow-lg': '0 20px 25px rgba(0,0,0,0.1)',
18
            },
19
            dark: {
20
                'theme-bg': '#121212',
21
                'theme-text': '#e4e4e4',
22
                'theme-text-secondary': '#a0a0a0',
23
                'theme-card-bg': '#1e1e1e',
24
                'theme-card-border': '#333333',
25
                'theme-input-bg': '#2d2d2d',
26
                'theme-input-border': '#404040',
27
                'theme-hover': '#2d2d2d',
28
                'theme-shadow': '0 4px 6px rgba(0,0,0,0.3)',
29
                'theme-shadow-lg': '0 20px 25px rgba(0,0,0,0.4)',
30
            },
31
            'high-contrast': {
32
                'theme-bg': '#ffffff',
33
                'theme-text': '#000000',
34
                'theme-text-secondary': '#000000',
35
                'theme-card-bg': '#ffffff',
36
                'theme-card-border': '#000000',
37
                'theme-input-bg': '#ffffff',
38
                'theme-input-border': '#000000',
39
                'theme-hover': '#f0f0f0',
40
                'theme-shadow': 'none',
41
                'theme-shadow-lg': 'none',
42
            }
43
        };
44
        
45
        this.applyTheme(this.currentTheme);
46
        this.setupSystemPreferenceListener();
47
    }
48
    
49
    loadTheme() {
50
        return localStorage.getItem('theme');
51
    }
52
    
53
    saveTheme(theme) {
54
        localStorage.setItem('theme', theme);
55
    }
56
    
57
    applyTheme(theme) {
58
        if (!this.themes[theme]) return;
59
        
60
        // 设置 data-theme 属性(用于 CSS 选择器)
61
        this.root.setAttribute('data-theme', theme);
62
        
63
        // 通过 CSS 变量应用主题
64
        const themeVars = this.themes[theme];
65
        Object.entries(themeVars).forEach(([key, value]) => {
66
            this.root.style.setProperty(`--${key}`, value);
67
        });
68
        
69
        this.currentTheme = theme;
70
        this.saveTheme(theme);
71
        this.dispatchThemeChange(theme);
72
    }
73
    
74
    toggleTheme() {
75
        const themes = ['light', 'dark'];
76
        const nextIndex = (themes.indexOf(this.currentTheme) + 1) % themes.length;
77
        this.applyTheme(themes[nextIndex]);
78
    }
79
    
80
    getCurrentTheme() {
81
        return this.currentTheme;
82
    }
83
    
84
    setupSystemPreferenceListener() {
85
        // 监听系统主题变化
86
        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
87
        mediaQuery.addEventListener('change', (e) => {
88
            if (!localStorage.getItem('theme')) {
89
                this.applyTheme(e.matches ? 'dark' : 'light');
90
            }
91
        });
92
    }
93
    
94
    dispatchThemeChange(theme) {
95
        window.dispatchEvent(new CustomEvent('themeChange', { detail: { theme } }));
96
    }
97
}
98
99
// 使用
100
const themeManager = new ThemeManager();
101
102
// 切换主题
103
document.querySelector('#theme-toggle').addEventListener('click', () => {
104
    themeManager.toggleTheme();
105
});
106
107
// 监听主题变化
108
window.addEventListener('themeChange', (e) => {
109
    console.log('主题已切换为:', e.detail.theme);
110
});

6.2 CSS 自定义属性与动画控制

1
// 动态控制 CSS 动画参数
2
class AnimationController {
3
    constructor() {
4
        this.root = document.documentElement;
5
        this.defaults = {
6
            duration: 0.3,
7
            easing: 'ease',
8
            delay: 0
9
        };
10
    }
11
    
12
    setAnimation(selector, properties) {
13
        const element = document.querySelector(selector);
14
        if (!element) return;
15
        
16
        // 通过 CSS 变量控制动画参数
17
        const { duration, easing, delay } = { ...this.defaults, ...properties };
18
        
19
        element.style.setProperty('--anim-duration', `${duration}s`);
20
        element.style.setProperty('--anim-easing', easing);
21
        element.style.setProperty('--anim-delay', `${delay}s`);
22
    }
23
    
24
    animateIn(selector) {
25
        this.setAnimation(selector, { duration: 0.5, easing: 'cubic-bezier(0.34, 1.56, 0.64, 1)' });
26
        document.querySelector(selector)?.classList.add('anim-in');
27
    }
28
    
29
    animateOut(selector) {
30
        this.setAnimation(selector, { duration: 0.3, easing: 'ease-in' });
31
        document.querySelector(selector)?.classList.add('anim-out');
32
    }
33
}
34
35
// CSS 中对应的动画定义
36
/*
37
.anim-in {
38
    animation: fadeInUp var(--anim-duration, 0.3s) var(--anim-easing, ease) var(--anim-delay, 0s) forwards;
39
}
40
41
.anim-out {
42
    animation: fadeOutDown var(--anim-duration, 0.3s) var(--anim-easing, ease) var(--anim-delay, 0s) forwards;
43
}
44
45
@keyframes fadeInUp {
46
    from {
47
        opacity: 0;
48
        transform: translateY(20px);
49
    }
50
    to {
51
        opacity: 1;
52
        transform: translateY(0);
53
    }
54
}
55
56
@keyframes fadeOutDown {
57
    from {
58
        opacity: 1;
59
        transform: translateY(0);
60
    }
61
    to {
62
        opacity: 0;
63
        transform: translateY(20px);
64
    }
65
}
66
*/

6.3 响应式断点的 JavaScript 管理

1
// 将 CSS 断点暴露给 JavaScript
2
class BreakpointManager {
3
    constructor() {
4
        this.breakpoints = {
5
            sm: 640,
6
            md: 768,
7
            lg: 1024,
8
            xl: 1280,
9
            '2xl': 1536
10
        };
11
        
12
        this.current = this.detect();
13
        this.setupListener();
14
    }
15
    
16
    detect() {
17
        const width = window.innerWidth;
18
        let current = 'xs';
19
        
20
        for (const [name, size] of Object.entries(this.breakpoints)) {
21
            if (width >= size) {
22
                current = name;
23
            }
24
        }
25
        
26
        return current;
27
    }
28
    
29
    setupListener() {
30
        let timeout;
31
        window.addEventListener('resize', () => {
32
            clearTimeout(timeout);
33
            timeout = setTimeout(() => {
34
                const newBreakpoint = this.detect();
35
                if (newBreakpoint !== this.current) {
36
                    this.current = newBreakpoint;
37
                    window.dispatchEvent(new CustomEvent('breakpointChange', {
38
                        detail: { breakpoint: this.current }
39
                    }));
40
                }
41
            }, 100);
42
        });
43
    }
44
    
45
    isAbove(breakpoint) {
46
        const sizes = Object.values(this.breakpoints);
47
        const currentWidth = window.innerWidth;
48
        return currentWidth >= (this.breakpoints[breakpoint] || 0);
49
    }
50
    
51
    isBelow(breakpoint) {
52
        const sizes = Object.values(this.breakpoints);
53
        const currentWidth = window.innerWidth;
54
        return currentWidth < (this.breakpoints[breakpoint] || 0);
55
    }
56
}
57
58
// 使用
59
const breakpoints = new BreakpointManager();
60
61
// 监听断点变化
62
window.addEventListener('breakpointChange', (e) => {
63
    console.log('当前断点:', e.detail.breakpoint);
64
});
65
66
// 条件性执行
67
if (breakpoints.isAbove('lg')) {
68
    // 在大屏幕上执行特定逻辑
69
}

6.4 高性能动画与 requestAnimationFrame

1
// 使用 requestAnimationFrame 驱动 CSS 变量动画
2
class VariableAnimation {
3
    constructor(element, variableName, config) {
4
        this.element = element;
5
        this.variableName = variableName;
6
        this.config = {
7
            from: 0,
8
            to: 1,
9
            duration: 1000,
10
            easing: this.easeInOut,
11
            ...config
12
        };
13
        this.running = false;
14
    }
15
    
16
    easeInOut(t) {
17
        return t < 0.5
18
            ? 4 * t * t * t
19
            : 1 - Math.pow(-2 * t + 2, 3) / 2;
20
    }
21
    
22
    start() {
23
        if (this.running) return;
24
        this.running = true;
25
        this.startTime = performance.now();
26
        this.animate();
27
    }
28
    
29
    animate() {
30
        if (!this.running) return;
31
        
32
        const elapsed = performance.now() - this.startTime;
33
        const progress = Math.min(elapsed / this.config.duration, 1);
34
        const easedProgress = this.config.easing(progress);
35
        
36
        const value = this.config.from + (this.config.to - this.config.from) * easedProgress;
37
        this.element.style.setProperty(this.variableName, value);
38
        
39
        if (progress < 1) {
40
            requestAnimationFrame(() => this.animate());
41
        } else {
42
            this.running = false;
43
            this.element.style.setProperty(this.variableName, this.config.to);
44
        }
45
    }
46
    
47
    stop() {
48
        this.running = false;
49
    }
50
}
51
52
// 使用示例
53
const element = document.querySelector('.progress-bar');
54
const anim = new VariableAnimation(element, '--progress', {
55
    from: 0,
56
    to: 100,
57
    duration: 2000
58
});
59
anim.start();

第七章:CSS 最新演进特性

7.1 CSS 嵌套(Nesting)

CSS 嵌套模块让样式表结构更清晰,更接近 HTML 结构。

1
/* 传统写法 */
2
.card { padding: 20px; }
3
.card .card-title { font-size: 1.5rem; }
4
.card .card-title:hover { color: blue; }
5
.card .card-body { padding: 16px; }
6
7
/* 嵌套写法 */
8
.card {
9
    padding: 20px;
10
    
11
    .card-title {
12
        font-size: 1.5rem;
13
        
14
        &:hover {
15
            color: blue;
16
        }
17
    }
18
    
19
    .card-body {
20
        padding: 16px;
21
    }
22
}
23
24
/* 更复杂的嵌套 */
25
.nav {
26
    display: flex;
27
    gap: 8px;
28
    
29
    &-list {
30
        list-style: none;
31
        padding: 0;
32
        margin: 0;
33
    }
34
    
35
    &-item {
36
        display: inline-block;
37
        
38
        &.active {
39
            background: var(--primary);
40
            color: white;
41
        }
42
    }
43
    
44
    &-link {
45
        text-decoration: none;
46
        padding: 8px 16px;
47
        display: block;
48
        
49
        &:hover {
50
            background: var(--hover-bg);
51
        }
52
        
53
        &::after {
54
            content: '→';
55
            margin-left: 4px;
56
        }
57
    }
58
}
59
60
/* 嵌套 @media 查询 */
61
.card {
62
    display: flex;
63
    flex-direction: column;
64
    
65
    @media (min-width: 768px) {
66
        flex-direction: row;
67
        
68
        .card-image {
69
            flex: 0 0 40%;
70
        }
71
    }
72
}

7.2 CSS 作用域(Scoping)

@scope 规则允许精确控制样式的作用范围。

1
/* 基础作用域 */
2
@scope (.component) {
3
    .title { font-weight: bold; }
4
    .body { padding: 1rem; }
5
}
6
7
/* 带限制的作用域 */
8
@scope (.card) to (.card-inner) {
9
    .title {
10
        /* 只应用于 .card 的直接子级 .title,不包括 .card-inner 内部的 */
11
    }
12
}
13
14
/* 作用域的嵌套 */
15
@scope (.sidebar) {
16
    .nav-item { padding: 8px; }
17
    
18
    @scope (.nav-section) {
19
        .nav-item { padding-left: 24px; }
20
    }
21
}

7.3 CSS 函数与混入(Functions and Mixins)

CSS Functions and Mixins 模块(W3C 工作草案)将带来真正的"代码复用"能力。

1
/* 定义自定义函数(草案语法) */
2
@function --fluid-font(--min, --pref, --max) {
3
    result: clamp(var(--min), var(--pref), var(--max));
4
}
5
6
/* 使用自定义函数 */
7
.heading {
8
    font-size: --fluid-font(1.5rem, 4vw, 3rem);
9
}
10
11
/* 定义混入(Mixin) */
12
@mixin --card-styles(--bg, --radius, --shadow) {
13
    background: var(--bg);
14
    border-radius: var(--radius);
15
    box-shadow: var(--shadow);
16
    padding: 1.5rem;
17
}
18
19
/* 使用混入 */
20
.card-primary {
21
    @apply --card-styles(white, 8px, var(--shadow-md));
22
}
23
24
.card-dark {
25
    @apply --card-styles(#1a1a1a, 12px, var(--shadow-lg));
26
}

7.4 CSS 滚动驱动动画(Scroll-driven Animations)

滚动驱动动画允许动画由滚动进度控制。

1
/* 滚动进度驱动的动画 */
2
@keyframes progress {
3
    from { width: 0%; }
4
    to { width: 100%; }
5
}
6
7
.progress-bar {
8
    animation: progress linear;
9
    animation-timeline: scroll(root);
10
    animation-range: contain;
11
}
12
13
/* 滚动进入视口触发动画 */
14
@keyframes fadeIn {
15
    from { opacity: 0; transform: translateY(20px); }
16
    to { opacity: 1; transform: translateY(0); }
17
}
18
19
.anim-on-scroll {
20
    animation: fadeIn ease both;
21
    animation-timeline: view();
22
    animation-range: entry 0% entry 100%;
23
}
24
25
/* 固定元素跟随滚动 */
26
.sticky-element {
27
    position: sticky;
28
    top: 20px;
29
    animation: sticky-rotate linear;
30
    animation-timeline: scroll(root);
31
    animation-range: contain;
32
}
33
34
@keyframes sticky-rotate {
35
    from { transform: rotate(0deg); }
36
    to { transform: rotate(360deg); }
37
}

7.5 CSS 视图过渡(View Transitions)

视图过渡 API 允许在页面状态变化时创建平滑的动画过渡。

1
/* 定义视图过渡 */
2
::view-transition-old(root) {
3
    animation: fadeOut 0.3s ease forwards;
4
}
5
6
::view-transition-new(root) {
7
    animation: fadeIn 0.3s ease forwards;
8
}
9
10
@keyframes fadeOut {
11
    from { opacity: 1; }
12
    to { opacity: 0; }
13
}
14
15
@keyframes fadeIn {
16
    from { opacity: 0; }
17
    to { opacity: 1; }
18
}
19
20
/* 命名过渡 */
21
.smooth-transition {
22
    view-transition-name: main-content;
23
}

7.6 CSS :has() 选择器

:has() 选择器允许根据子元素或后续兄弟元素来选择父元素。

1
/* 选择包含图片的卡片 */
2
.card:has(img) {
3
    padding: 0;
4
}
5
6
/* 选择包含特定标题的卡片 */
7
.card:has(.card-title) {
8
    background: var(--highlight-bg);
9
}
10
11
/* 选择包含按钮的容器 */
12
.container:has(.btn-primary) {
13
    border-color: var(--primary);
14
}
15
16
/* 选择有输入错误的表单 */
17
.form-group:has(.input:invalid) {
18
    .form-label {
19
        color: var(--danger);
20
    }
21
}
22
23
/* 选择包含特定内容的文章 */
24
.article:has(h2:nth-of-type(3)) {
25
    /* 包含第三个 h2 的文章 */
26
}
27
28
/* 选择有兄弟元素 .sidebar 的 main */
29
main:has(~ .sidebar) {
30
    grid-template-columns: 1fr 300px;
31
}
32
33
/* 选择被选中的复选框的父标签 */
34
label:has(input:checked) {
35
    font-weight: bold;
36
    color: var(--primary);
37
}

第八章:CSS 性能优化与最佳实践

8.1 选择器性能

1
/* 性能较差:通配选择器 + 后代选择器 */
2
* .item { /* 需要检查所有元素 */ }
3
4
/* 性能较好:直接类选择器 */
5
.item { /* 直接匹配,效率高 */ }
6
7
/* 性能较差:复杂伪类 */
8
ul li:last-child { /* 需要遍历子元素 */ }
9
10
/* 性能较好:使用类 + 结构伪类结合 */
11
.item:last-child { /* 更直接的匹配 */ }
12
13
/* 性能较差:属性选择器(使用频繁) */
14
input[type="text"] { /* 属性匹配较慢 */ }
15
16
/* 性能较好:为特定类型添加类 */
17
.input-text { /* 类匹配较快 */ }

8.2 重排与重绘优化

1
/* 触发重排(Reflow)的属性:width, height, margin, padding, display, position, float, top, left 等 */
2
/* 触发重绘(Repaint)的属性:color, background, visibility, outline 等 */
3
/* 不触发重排和重绘的属性:transform, opacity 等 */
4
5
/* 推荐:使用 transform 和 opacity 做动画 */
6
.element {
7
    transition: transform 0.3s ease, opacity 0.3s ease;
8
}
9
10
.element:hover {
11
    transform: scale(1.05);
12
    opacity: 0.9;
13
}
14
15
/* 避免:使用触发重排的属性做动画 */
16
.element {
17
    transition: width 0.3s ease, height 0.3s ease;
18
}
19
20
.element:hover {
21
    width: 120px;
22
    height: 120px;
23
}

8.3 高效使用 CSS 变量

1
/* 推荐:在需要动态变化的地方使用变量 */
2
:root {
3
    --color: #3498db;
4
}
5
6
.button {
7
    background: var(--color);
8
    /* 变量值变化时,只触发重绘,不触发重排 */
9
}
10
11
/* 避免:在触发重排的属性上过度使用变量 */
12
:root {
13
    --width: 100px;
14
    --height: 100px;
15
    --margin: 10px;
16
}
17
18
.element {
19
    /* 这些属性变化会触发重排 */
20
    width: var(--width);
21
    height: var(--height);
22
    margin: var(--margin);
23
}

8.4 CSS 代码组织最佳实践

1
/* 1. 使用 @layer 组织代码层级 */
2
@layer reset, base, components, utilities;
3
4
/* 2. 文件结构(推荐) */
5
/* styles/
6
├── tokens/
7
│   ├── colors.css
8
│   ├── typography.css
9
│   └── spacing.css
10
├── base/
11
│   ├── reset.css
12
│   ├── typography.css
13
│   └── forms.css
14
├── components/
15
│   ├── button.css
16
│   ├── card.css
17
│   └── modal.css
18
├── layouts/
19
│   ├── header.css
20
│   ├── footer.css
21
│   └── grid.css
22
└── utilities/
23
    ├── spacing.css
24
    ├── text.css
25
    └── display.css
26
*/
27
28
/* 3. 命名约定(BEM) */
29
/* Block */
30
.card { /* ... */ }
31
32
/* Element */
33
.card__title { /* ... */ }
34
.card__body { /* ... */ }
35
.card__footer { /* ... */ }
36
37
/* Modifier */
38
.card--featured { /* ... */ }
39
.card__title--large { /* ... */ }
40
41
/* 4. 响应式设计模式 */
42
/* 移动优先 */
43
.element {
44
    /* 移动端样式(默认) */
45
    padding: 8px;
46
    font-size: 14px;
47
}
48
49
@media (min-width: 768px) {
50
    .element {
51
        /* 平板样式 */
52
        padding: 16px;
53
        font-size: 16px;
54
    }
55
}
56
57
@media (min-width: 1024px) {
58
    .element {
59
        /* 桌面样式 */
60
        padding: 24px;
61
        font-size: 18px;
62
    }
63
}

总结

CSS 已经从单纯的“描述性语言”演变成为一种工程化的设计语言。它拥有了变量、运算、条件逻辑、模块化等编程语言的特性,让开发者能够构建复杂、可维护、可扩展的样式系统。

本文完整系统地讲解了 CSS 编程的各个方面:

  • CSS 变量:实现了样式的存储、复用和动态控制
  • 运算与函数:提供了数学计算、颜色处理等能力
  • 条件逻辑:通过 @media、@supports、@container 实现了响应式和特性检测
  • 模块化与作用域:通过 @layer、@scope、CSS 模块等实现了样式封装
  • 设计系统:构建了完整的令牌体系和主题系统
  • CSS 与 JavaScript 协同:实现了动态样式控制和主题切换
  • 最新演进特性:涵盖了嵌套、:has()、视图过渡等现代特性

“CSS 编程”的核心在于:用编程思维组织样式代码、用工程化手段管理设计系统、用声明式方式表达视觉逻辑。理解这一点,你就能真正驾驭 CSS,让它成为构建 Web 应用最得心应手的工具之一。