第 7 章 · 颜色、字体与组件样式
本章目标:为 academy-demo 建立可维护的 设计令牌(Design Tokens) 与 CSS 变量体系,统一配色、字体、间距与按钮/卡片/表单组件,达到 WCAG 可访问基线。
学时建议:2 小时(含 45 分钟整理 theme.css)
前置:frontend-web ch04~06;理解类选择器、box-shadow 与 :hover / :focus。
7.1 设计系统分层
academy-demo/css/
├── reset.css # 浏览器默认样式重置
├── theme.css # 本章:设计令牌 + 组件
└── layout.css # 仅 Flex / Grid 布局
| 层级 | 内容 | 修改频率 |
|---|---|---|
令牌 :root | 颜色、字号、间距、圆角、阴影 | 品牌变更时 |
组件 .btn、.card | 可复用 UI 块 | 中 |
布局 .site-header | 结构定位 | ch05~06 |
专业原则:组件只引用var(--token),禁止在业务类内硬编码#e91e8c;换肤时只改:root。
7.2 设计令牌:CSS 变量体系
/* theme.css — academy-demo Design Tokens */
:root {
/* 品牌色 */
--color-primary: #e91e8c;
--color-primary-dark: #c2185b;
--color-primary-rgb: 233, 30, 140;
/* 中性色 */
--color-bg: #f8fafc;
--color-surface: #ffffff;
--color-text: #1e293b;
--color-muted: #64748b;
--color-border: #e2e8f0;
/* 语义色 */
--color-success: #16a34a;
--color-warning: #d97706;
--color-danger: #dc2626;
/* 字体 */
--font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI",
"PingFang SC", "Microsoft YaHei", sans-serif;
--font-mono: "Cascadia Code", Consolas, monospace;
--text-xs: 0.75rem;
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.125rem;
--text-2xl: 1.5rem;
--text-3xl: 2rem;
--font-semibold: 600;
--font-bold: 700;
--leading-normal: 1.6;
/* 间距(4px 基准) */
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 0.75rem;
--space-4: 1rem;
--space-5: 1.25rem;
--space-8: 2rem;
/* 圆角与阴影 */
--radius-md: 8px;
--radius-xl: 16px;
--radius-full: 9999px;
--shadow-md: 0 8px 24px rgba(15, 23, 42, 0.06);
--shadow-primary: 0 4px 14px rgba(var(--color-primary-rgb), 0.3);
/* 动效与焦点 */
--duration-fast: 150ms;
--focus-ring: 0 0 0 3px rgba(var(--color-primary-rgb), 0.25);
}
| 前缀 | 含义 | 示例 |
|---|---|---|
--color-* | 颜色 | --color-text |
--text- / --font- | 字号与字重 | --text-lg |
--space-* | 间距 | --space-4 |
--radius- / --shadow- | 圆角与阴影 | --radius-xl |
暗色主题:用 @media (prefers-color-scheme: dark) 或 html[data-theme="dark"] 覆写中性色令牌,并重新检查对比度。
7.3 配色、字体与 WCAG
| 组合 | 最低对比度(AA) | 检查方式 |
|---|---|---|
| 正文 / 背景 | 4.5 : 1 | DevTools → 对比度检查 |
| 大号文字 | 3 : 1 | 同上 |
| UI 边界 | 3 : 1 | 按钮边框、输入框 |
body {
font-family: var(--font-sans);
font-size: var(--text-base);
line-height: var(--leading-normal);
color: var(--color-text);
background: var(--color-bg);
}
h1 { font-size: var(--text-3xl); font-weight: var(--font-bold); }
h2 { font-size: var(--text-2xl); margin-block: var(--space-8) var(--space-4); }
h3 { font-size: var(--text-lg); font-weight: var(--font-semibold); }
.text-muted { color: var(--color-muted); font-size: var(--text-sm); }
code, pre { font-family: var(--font-mono); }
勿仅靠颜色传达状态:错误除红框外,应有文案(如「请输入有效邮箱」)。