CSS 与设计体系完全指南
NOTE
本文档最后更新于 2026年4月,涵盖现代 CSS 布局体系、设计系统、动画运动、可访问性及 AI 辅助设计工具链,是 vibecoding 时代每个前端开发者必须掌握的设计技能集合。
目录
- CSS 概述与现代化定位
- CSS 布局体系:从 Flexbox 到 Grid
- CSS 盒模型与视觉格式化
- 响应式设计策略
- 现代 CSS 特性:Custom Properties / Container Queries / Cascade Layers
- CSS 动画与运动设计
- 设计系统与组件化样式
- Tailwind CSS 深度指南
- AI 编程中的 CSS 最佳实践
- 选型建议与性能优化
CSS 概述与现代化定位
CSS 在 vibecoding 时代的角色变迁
CSS 在过去十年经历了革命性的演进。从最初的「给 HTML 上色」工具,如今已发展为包含布局系统、动画引擎、逻辑控制、容器查询等能力的完整设计语言体系。在 AI 编程时代,CSS 的重要性不降反升——AI 可以快速生成组件结构,但视觉细节、响应式行为、动画节奏、主题切换等设计层面的工作,仍需要开发者具备扎实的 CSS 素养才能有效把控。
根据 2026 年 CSS 现状调查(CSS State Survey 2026):
- 96% 的前端开发者使用 CSS 框架(Tailwind CSS 占比 52%,首次超越 Bootstrap)
- 78% 的项目采用 CSS 自定义属性(Custom Properties)进行主题管理
- 63% 的现代项目使用 CSS Grid 作为主要布局工具
- 45% 的团队建立了完整的设计系统(Design System)
CSS 技术栈全景图
CSS 技术栈
├── 布局系统
│ ├── Flexbox — 一维布局、对齐、分配
│ ├── CSS Grid — 二维布局、页面结构
│ └── Subgrid — Grid 子级对齐
├── 样式工具
│ ├── Tailwind CSS — 原子化实用优先
│ ├── CSS Modules — 作用域隔离
│ ├── Styled Components — 模板字面量样式
│ └── CSS-in-JS — JavaScript 驱动样式
├── 设计系统
│ ├── Design Tokens — 设计变量标准化
│ ├── shadcn/ui — 可复制组件设计
│ ├── Radix UI — 无头组件库
│ └── Design System 架构
├── 动画运动
│ ├── CSS Transitions — 状态过渡
│ ├── CSS Animations — 关键帧动画
│ ├── View Transitions — 视图过渡
│ └── Motion 哲学与原则
├── 现代特性
│ ├── Custom Properties — CSS 变量
│ ├── Container Queries — 容器查询
│ ├── Cascade Layers — 级联层
│ ├── :has() 选择器 — 父选择器
│ └── Color Functions — 色彩函数
└── 工程化
├── PostCSS — CSS 转换与增强
├── Sass/SCSS — CSS 预处理器
├── Stylelint — CSS 代码质量
└── PurgeCSS — 无用样式清除
CSS 布局体系:从 Flexbox 到 Grid
布局进化史
CSS 布局经历了三个阶段:
| 阶段 | 时代 | 核心技术 | 局限 |
|---|---|---|---|
| 古典时代 | 2000-2010 | Float + Position | 居中困难、垂直等高无法实现 |
| 框架时代 | 2010-2017 | Bootstrap Grid | 冗余类名、定制困难 |
| 现代时代 | 2017-至今 | Flexbox + Grid | 完全掌控、无历史包袱 |
Flexbox 深入指南
Flexbox 是目前使用最广泛的 CSS 布局工具,特别适合以下场景:
- 导航栏:水平排列、等宽分配
- 卡片列表:自动换行、均匀分布
- 弹窗:水平垂直居中
- 表单:标签与输入框对齐
/* Flexbox 核心概念 */
.flex-container {
/* 激活 flex 上下文 */
display: flex;
/* 主轴方向(默认 row) */
flex-direction: row; /* 行(默认)*/
flex-direction: column; /* 列 */
flex-direction: row-reverse; /* 反向行 */
/* 主轴对齐(默认 flex-start)*/
justify-content: flex-start; /* 左对齐 */
justify-content: center; /* 居中 */
justify-content: space-between; /* 两端对齐 */
justify-content: space-around; /* 等宽环绕 */
justify-content: space-evenly; /* 完全等距 */
/* 交叉轴对齐(默认 stretch)*/
align-items: stretch; /* 拉伸填满 */
align-items: center; /* 居中对齐 */
align-items: baseline; /* 基线对齐 */
/* 换行控制(默认 nowrap)*/
flex-wrap: nowrap; /* 不换行(默认)*/
flex-wrap: wrap; /* 允许换行 */
flex-wrap: wrap-reverse; /* 反向换行 */
/* 多行对齐(仅 wrap 模式生效)*/
align-content: flex-start; /* 顶部对齐 */
align-content: center; /* 居中对齐 */
align-content: space-between; /* 两端对齐 */
}
/* Flex 子项属性 */
.flex-item {
/* 增长因子(默认 0)*/
flex-grow: 1; /* 等比增长 */
flex-grow: 2; /* 增长量是其他项的2倍 */
/* 收缩因子(默认 1)*/
flex-shrink: 0; /* 不收缩 */
/* 基础尺寸(默认 auto)*/
flex-basis: 200px; /* 固定基准 */
flex-basis: 50%; /* 百分比基准 */
flex-basis: auto; /* 依据自身尺寸(默认)*/
/* 简写:flex: grow shrink basis */
flex: 1; /* flex: 1 1 0% */
flex: 0 0 200px; /* 固定宽度不伸缩 */
flex: auto; /* flex: 1 1 auto */
flex: none; /* flex: 0 0 auto */
/* 单独覆盖交叉轴对齐 */
align-self: center; /* 垂直居中 */
align-self: flex-end; /* 底部对齐 */
}Flexbox 实战:经典布局模式
1. 圣杯布局(Holy Grail Layout)
/* 经典圣杯:header + main + aside + footer */
.layout {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header, .footer {
flex: 0 0 auto;
}
.main-wrapper {
display: flex;
flex: 1;
min-height: 0; /* 关键:允许收缩 */
}
.main {
flex: 1;
min-width: 0; /* 关键:文字溢出截断 */
}
.aside-left, .aside-right {
flex: 0 0 250px;
}
@media (max-width: 768px) {
.main-wrapper {
flex-direction: column;
}
.aside-left, .aside-right {
flex: 0 0 auto;
}
}2. 均等卡片网格
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.card {
/* 自动计算:每行容纳尽可能多的卡片 */
flex: 1 1 300px; /* 最小 300px,增长填充 */
max-width: 400px; /* 最大 400px */
}
/* 更精细的控制:固定行数 */
.card-grid-fixed {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.card-exact {
/* 每行恰好 3 个 */
flex: 0 1 calc((100% - 2 * 16px) / 3);
}3. 粘性 footer(Sticky Footer)
.page-wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main-content {
flex: 1;
}
/* 传统方案需要 margin-bottom: auto */
/* 现代方案由 flex 直接撑满 */CSS Grid 深入指南
CSS Grid 是二维布局系统,最适合页面级整体布局和复杂网格式设计。
/* Grid 基础 */
.grid-container {
display: grid;
/* 定义列:固定 + 自适应 + 重复 */
grid-template-columns: 200px 1fr 200px; /* 固定+弹性+固定 */
grid-template-columns: repeat(3, 1fr); /* 三等列 */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* 自动响应式 */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* 定义行 */
grid-template-rows: auto 1fr auto;
/* 间距 */
gap: 24px;
row-gap: 16px;
column-gap: 32px;
/* 网格区域命名 */
grid-template-areas:
"header header header"
"sidebar main aside"
"footer footer footer";
}
/* 命名网格线 */
.grid-named {
display: grid;
grid-template-columns:
[full-start] 1fr
[content-start] min(65ch, 100%)
[content-end] 1fr
[full-end];
}
.content {
grid-column: content-start / content-end; /* 限制最大宽度 */
}
.full-bleed {
grid-column: full-start / full-end; /* 全宽铺开 */
}Grid 定位与合并
/* 放置网格项 */
.grid-item {
/* 按网格线定位 */
grid-column: 1 / 3; /* 从第1列线到第3列线 */
grid-column: 1 / span 2; /* 从第1列线跨2列 */
grid-column: 1 / -1; /* 跨越到最后 */
grid-row: 2 / 4; /* 从第2行线到第4行线 */
/* 命名区域 */
grid-area: header; /* 占据 header 区域 */
/* 单元格对齐 */
justify-self: start; /* 水平对齐(默认 stretch)*/
align-self: end; /* 垂直对齐(默认 stretch)*/
place-self: center; /* 两者合一:居中 */
}
/* 隐式网格(超出定义范围的项)*/
.auto-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
auto-rows: 200px; /* 隐式行高 */
gap: 16px;
}Subgrid:子级对齐
Subgrid 是 Grid 的里程碑特性,解决了子组件需要对齐父网格的问题:
/* 父网格 */
.card-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto 1fr auto;
gap: 24px;
}
/* 子网格:继承父网格轨道 */
.card {
display: grid;
grid-template-columns: subgrid; /* 继承父的列定义 */
grid-template-rows: subgrid; /* 继承父的行定义 */
grid-row: span 3; /* 跨越所有行 */
}
/* 结果:card 内部的 header/content/footer 自动对齐到父网格 */Flexbox vs Grid 决策指南
| 场景 | 推荐方案 | 原因 |
|---|---|---|
| 导航栏按钮均匀分布 | Flexbox | 一维排列、简单对齐 |
| 卡片列表自动换行 | Flexbox / Grid | 均可,Grid 更适合固定列数 |
| 页面整体布局 | Grid | 二维控制、命名区域 |
| 垂直居中任意元素 | Flexbox | 一行代码 |
| 组件内部元素对齐 | Flexbox | 单容器内对齐 |
| 复杂报表/仪表盘 | Grid | 精确行列控制 |
| 需要浏览器兼容 IE11 | Flexbox | Grid IE 支持有限 |
CSS 盒模型与视觉格式化
盒模型详解
CSS 有两种盒模型:
/* 标准盒模型(content-box,默认)*/
.content-box {
box-sizing: content-box;
width: 200px; /* 仅内容区 200px */
padding: 20px; /* 内边距额外增加 */
border: 1px solid #ccc; /* 边框额外增加 */
/* 总宽度:200 + 40 + 2 = 242px */
}
/* 怪异盒模型(border-box,推荐)*/
.border-box {
box-sizing: border-box;
width: 200px; /* 包含内容+padding+border */
padding: 20px;
border: 1px solid #ccc;
/* 总宽度:正好 200px */
}
/* 全局设置 border-box */
*, *::before, *::after {
box-sizing: border-box;
}TIP
推荐始终使用
box-sizing: border-box,这是 Tailwind CSS、Bootstrap 等框架的默认行为,也是最符合直觉的模型。
外边距折叠(Margin Collapsing)
外边距折叠是 CSS 中最容易被误解的特性之一:
/* 垂直外边距会折叠 */
.block-1 {
margin-bottom: 24px;
}
.block-2 {
margin-top: 16px;
}
/* 实际间距:max(24px, 16px) = 24px,而非 40px */
/* 折叠的三个条件 */
.collapse-conditions {
/* 1. 块级元素 */
display: block; /* 行内元素不折叠 */
/* 2. 正常流中 */
position: absolute; /* 定位元素不折叠 */
float: left; /* 浮动元素不折叠 */
/* 3. 同一包含块中 */
}
/* 阻止折叠的方法 */
.no-collapse {
/* 方法1:使用 padding 替代 margin */
padding-bottom: 24px;
/* 方法2:添加边框分隔 */
border-bottom: 1px solid transparent;
/* 方法3:创建块格式化上下文(BFC)*/
overflow: hidden;
/* 或 */
display: flow-root; /* 纯 BFC 创建方式 */
}BFC(块格式化上下文)
BFC 是一个独立的渲染区域,其中的布局不受外部影响:
/* 创建 BFC 的方式 */
.bfc {
/* 方式1:overflow(非 visible)*/
overflow: hidden;
overflow: auto;
/* 方式2:display: flow-root(推荐,无副作用)*/
display: flow-root;
/* 方式3:float */
float: left; /* 或 right */
/* 方式4:position */
position: absolute;
position: fixed;
/* 方式5:display */
display: inline-block;
display: table-cell;
}
/* BFC 的特性 */
.bfc-use-cases {
/* 1. 清除浮动 */
/* 2. 阻止外边距折叠 */
/* 3. 阻止文字环绕浮动元素 */
/* 4. 隔离布局(内部布局不影响外部)*/
}响应式设计策略
响应式设计三板斧
现代响应式设计遵循三个核心策略:
/* 1. 移动优先媒体查询 */
.container {
width: 100%;
padding: 16px;
}
/* 渐进增强 */
@media (min-width: 640px) {
.container {
padding: 24px;
}
}
@media (min-width: 1024px) {
.container {
max-width: 1200px;
padding: 32px;
}
}
/* 2. 弹性单位 */
.elastic-layout {
/* 视口单位 */
width: 100vw;
height: 100vh;
/* 相对单位 */
font-size: clamp(1rem, 2vw, 1.5rem); /* 动态字号 */
/* 弹性容器 */
display: flex;
flex-wrap: wrap;
gap: clamp(16px, 4vw, 48px); /* 动态间距 */
}
/* 3. 容器查询 */
.card-wrapper {
container-type: inline-size;
container-name: card;
}
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
}
}断点系统设计
/* 经典五断点系统 */
:root {
/* 移动端优先 */
--breakpoint-sm: 640px; /* 大手机横屏 */
--breakpoint-md: 768px; /* 平板 */
--breakpoint-lg: 1024px; /* 小笔记本 */
--breakpoint-xl: 1280px; /* 桌面 */
--breakpoint-2xl: 1536px; /* 大屏 */
}
/* 进阶:基于内容的断点 */
@media (max-width: 59.9em) { /* 当容器小于 60em */
.sidebar {
display: none; /* 隐藏侧边栏 */
}
}现代 CSS 特性
Custom Properties(CSS 变量)
:root {
/* 颜色系统 */
--color-primary: #3b82f6;
--color-primary-light: color-mix(in srgb, var(--color-primary) 80%, white);
--color-primary-dark: color-mix(in srgb, var(--color-primary) 80%, black);
/* 语义化颜色 */
--color-text: var(--color-gray-900);
--color-bg: var(--color-white);
/* 间距系统 */
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-6: 24px;
--space-8: 32px;
/* 圆角系统 */
--radius-sm: 4px;
--radius-md: 8px;
--radius-lg: 12px;
--radius-full: 9999px;
/* 阴影系统 */
--shadow-sm: 0 1px 2px rgb(0 0 0 / 0.05);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
/* 过渡系统 */
--transition-fast: 150ms ease;
--transition-base: 300ms ease;
--transition-slow: 500ms ease;
}
/* 动态主题切换 */
[data-theme="dark"] {
--color-bg: #0f172a;
--color-text: #f1f5f9;
--color-primary: #60a5fa;
}
/* 作用域覆盖 */
.card-dark {
--card-bg: #1e293b;
background: var(--card-bg, var(--color-bg));
}Container Queries(容器查询)
容器查询是响应式设计的范式跃迁:不再依赖视口大小,而是根据容器自身尺寸响应。
/* 定义容器 */
.card-container {
container-type: inline-size;
container-name: card;
}
/* 基础样式(默认小容器)*/
.product-card {
display: flex;
flex-direction: column;
}
.product-image {
aspect-ratio: 1;
}
/* 容器宽度 > 400px 时的样式 */
@container card (width >= 400px) {
.product-card {
flex-direction: row;
}
.product-image {
width: 40%;
aspect-ratio: auto;
}
}
/* 容器宽度 > 600px 时的样式 */
@container card (width >= 600px) {
.product-card {
gap: 32px;
}
}TIP
容器查询解决了「同一个组件在不同页面位置表现不同」的问题,是组件化开发的关键能力。
Cascade Layers(级联层)
/* 定义级联层优先级(后声明的层优先级更高)*/
@layer reset, base, components, utilities;
/* 每个层的样式互不影响 */
@layer reset {
* { margin: 0; padding: 0; }
}
@layer base {
h1 { font-size: 2rem; } /* 即使 !important 也不敌 utilities */
}
@layer components {
.btn { padding: 8px 16px; }
}
@layer utilities {
.hidden { display: none !important; }
}
/* 样式归属层 */
@layer components {
.card {
background: white;
border-radius: 8px;
}
}
/* 覆盖第三方库样式而不怕 specificity */
@layer utilities {
.third-party-class {
/* 稳稳地覆盖,无视 specificity 战争 */
}
}:has() 父选择器
/* :has() 实现了 CSS 史上第一个「父选择器」*/
/* 当 form 包含 invalid 输入时高亮 */
form:has(:invalid) {
border-color: red;
}
/* 当 label 关联的 checkbox 选中时高亮 */
label:has(:checked) {
background: #dbeafe;
color: #1e40af;
}
/* 列表最后一项隐藏 */
ul:has(> :last-child:only-child) {
/* 当列表只有一个子元素时 */
}
/* 栅格布局:无图片时卡片更紧凑 */
.card:has(.card-image) {
/* 有图片时 */
}
.card:not(:has(.card-image)) {
padding: var(--space-4);
}现代色彩函数
/* 颜色混合 */
.mixed {
background: color-mix(in srgb, #ff0000 50%, #0000ff);
/* 混合红蓝各50%,得到紫色 */
}
/* 相对颜色(动态生成变体)*/
.button {
--btn-bg: #3b82f6;
--btn-hover: oklch(
from var(--btn-bg)
calc(l + 0.1)
c
h
);
background: var(--btn-bg);
}
.button:hover {
background: var(--btn-hover); /* 自动生成更亮的悬停色 */
}
/* OKLCH:感知均匀的色彩空间 */
.oklch-color {
/* 相同 L 值看起来亮度一致 */
color: oklch(59% 0.15 250); /* 蓝色 */
color: oklch(59% 0.15 120); /* 绿色,同亮度不同色相 */
}CSS 动画与运动设计
CSS Transitions
适用于状态变化的平滑过渡:
.transition-btn {
/* 过渡属性(可指定多个)*/
transition:
background-color 200ms ease,
transform 150ms ease-out,
box-shadow 300ms ease-in-out;
/* 贝塞尔曲线控制 */
transition-timing-function: ease; /* 慢-快-慢 */
transition-timing-function: ease-in; /* 慢-快 */
transition-timing-function: ease-out; /* 快-慢 */
transition-timing-function: ease-in-out; /* 慢-快-慢 */
transition-timing-function: linear; /* 匀速 */
transition-timing-function: steps(4); /* 分步 */
transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1); /* 自定义(弹性)*/
}
/* 悬停效果 */
.transition-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgb(0 0 0 / 0.15);
}CSS Animations
适用于复杂的多阶段动画:
@keyframes fade-in-slide {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes pulse-glow {
0%, 100% {
box-shadow: 0 0 0 0 rgb(59 130 246 / 0.4);
}
50% {
box-shadow: 0 0 0 10px rgb(59 130 246 / 0);
}
}
.animated-element {
/* 动画名称 */
animation-name: fade-in-slide;
/* 持续时间 */
animation-duration: 400ms;
/* 缓动函数 */
animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
/* 延迟 */
animation-delay: 100ms;
/* 迭代次数 */
animation-iteration-count: 1; /* 播放一次 */
animation-iteration-count: 3; /* 播放三次 */
animation-iteration-count: infinite; /* 无限循环 */
/* 方向 */
animation-direction: normal; /* 正向 */
animation-direction: reverse; /* 反向 */
animation-direction: alternate; /* 正反交替 */
/* 填充模式(关键)*/
animation-fill-mode: forwards; /* 保持最终状态 */
animation-fill-mode: backwards; /* 显示初始状态 */
animation-fill-mode: both; /* 应用初始/最终状态 */
/* 简写 */
animation: fade-in-slide 400ms cubic-bezier(0.16, 1, 0.3, 1) 100ms both;
}View Transitions(视图过渡)
View Transitions API 是 2024 年引入的革命性特性,实现页面切换的丝滑过渡:
/* 启用视图过渡 */
@view-transition {
navigation: auto; /* SPA 路由自动应用 */
}
/* 自定义过渡效果 */
::view-transition-old(root) {
animation: 300ms ease-out both fade-out;
}
::view-transition-new(root) {
animation: 300ms ease-out both fade-in;
}
@keyframes fade-out {
to { opacity: 0; }
}
@keyframes fade-in {
from { opacity: 0; }
}
/* 命名过渡:只过渡特定元素 */
.hero {
view-transition-name: hero-image;
}
::view-transition-old(hero-image) {
animation: slide-out 300ms ease;
}
::view-transition-new(hero-image) {
animation: slide-in 300ms ease;
}运动哲学(Motion Principles)
/* 遵循 Google Material Design 运动原则 */
/* 1. 物理真实感:使用自然缓动 */
/* 快速进入,缓慢退出 */
.entry {
transition: transform 200ms cubic-bezier(0, 0, 0.2, 1),
opacity 200ms cubic-bezier(0, 0, 0.2, 1);
}
.exit {
transition: transform 150ms cubic-bezier(0.4, 0, 1, 1),
opacity 150ms cubic-bezier(0.4, 0, 1, 1);
}
/* 2. 尊重用户偏好:减少动画 */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
/* 3. 状态清晰:元素出现/消失动效 */
.list-enter {
animation: item-enter 300ms ease-out both;
}
.list-enter:nth-child(1) { animation-delay: 0ms; }
.list-enter:nth-child(2) { animation-delay: 50ms; }
.list-enter:nth-child(3) { animation-delay: 100ms; }
/* ... */设计系统与组件化样式
Design Tokens 架构
/* 第1层:原始值(Primitives)*/
--blue-500: #3b82f6;
--blue-600: #2563eb;
--spacing-4: 16px;
--radius-md: 8px;
/* 第2层:语义化变量 */
--color-action-primary: var(--blue-500);
--color-action-primary-hover: var(--blue-600);
--spacing-component-padding: var(--spacing-4);
--radius-component: var(--radius-md);
/* 第3层:组件变量 */
--button-bg: var(--color-action-primary);
--button-padding: var(--spacing-component-padding);
--button-radius: var(--radius-component);组件样式隔离方案对比
| 方案 | 特点 | 适用场景 | AI 友好度 |
|---|---|---|---|
| CSS Modules | 文件级作用域,简单直观 | React/Vue 项目 | 高 |
| CSS-in-JS | JS 对象驱动样式,动态能力强 | 高度动态主题 | 中 |
| Tailwind CSS | 原子化类名,无缝 AI 生成 | vibecoding 原生 | 极高 |
| CSS Custom Properties | 原生变量,运行时切换 | 主题系统 | 高 |
CSS Modules 示例
/* Card.module.css */
.card {
background: white;
border-radius: 8px;
box-shadow: var(--shadow-md);
padding: 24px;
transition: box-shadow var(--transition-base);
}
.card:hover {
box-shadow: var(--shadow-lg);
}
.header {
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 16px;
}
/* 组合变体 */
.card.featured {
border: 2px solid var(--color-primary);
background: var(--color-primary-subtle);
}
/* React 组件中使用 */// Card.tsx
import styles from './Card.module.css';
export function Card({ title, children, featured }) {
return (
<div className={`${styles.card} ${featured ? styles.featured : ''}`}>
<h3 className={styles.header}>{title}</h3>
<div className={styles.content}>{children}</div>
</div>
);
}Tailwind CSS 深度指南
Tailwind 的设计哲学
Tailwind CSS 的核心哲学是「实用优先」(Utility-First),通过组合原子化类名构建 UI,而非编写传统 CSS。
<!-- 等价于传统 CSS 需要 50+ 行代码 -->
<div class="flex items-center justify-between p-6 bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300">
<h2 class="text-xl font-semibold text-gray-900">标题</h2>
<button class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
操作
</button>
</div>Tailwind 核心配置
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
export default {
content: [
'./src/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
// 扩展默认配置
extend: {
// 自定义颜色
colors: {
brand: {
50: '#f0f9ff',
500: '#0ea5e9',
900: '#0c4a6e',
},
},
// 自定义间距
spacing: {
'128': '32rem',
'144': '36rem',
},
// 自定义动画
keyframes: {
'fade-in': {
'0%': { opacity: '0', transform: 'translateY(10px)' },
'100%': { opacity: '1', transform: 'translateY(0)' },
},
'slide-in-right': {
'0%': { transform: 'translateX(100%)' },
'100%': { transform: 'translateX(0)' },
},
},
animation: {
'fade-in': 'fade-in 0.4s ease-out',
'slide-in-right': 'slide-in-right 0.3s ease-out',
},
// 字体
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
},
},
},
// 插件生态
plugins: [
require('@tailwindcss/forms'), // 表单样式重置
require('@tailwindcss/typography'), // Prose 内容排版
require('@tailwindcss/line-clamp'), // 文字截断
],
}Tailwind + shadcn/ui 组合
shadcn/ui 是与 Tailwind 深度配合的可复制组件库,每个组件都是源代码而非 npm 包:
# 安装 shadcn/ui
npx shadcn@latest init
# 添加组件
npx shadcn@latest add button card dialog dropdown-menu// 使用 shadcn/ui 组件
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog';
// 组合使用
<Card className="w-[350px]">
<CardHeader>
<CardTitle>卡片标题</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
卡片内容
</p>
</CardContent>
</Card>Tailwind 响应式与变体
<!-- 响应式前缀 -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- 移动端1列,平板2列,桌面3列 -->
</div>
<!-- 悬停、聚焦等交互状态 -->
<button class="
bg-blue-500 hover:bg-blue-600
focus:ring-2 focus:ring-blue-300
active:bg-blue-700
disabled:opacity-50 disabled:cursor-not-allowed
transition-colors duration-200
">
按钮
</button>
<!-- 暗色模式 -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
自适应内容
</div>
<!-- 容器查询 -->
<div class="[@media(min-width:800px)]:flex">
容器宽度超过 800px 时显示为 flex
</div>AI 辅助 Tailwind 开发技巧
<!-- 告诉 AI:使用 Tailwind 的原子类 -->
<!-- 避免让 AI 生成 CSS 文件 -->
<!-- 直接用类名组合实现设计 -->
<!-- 常用模式 -->
<!-- Flex 居中 -->
<div class="flex items-center justify-center">内容</div>
<!-- Grid 均等分布 -->
<div class="grid grid-cols-3 gap-4">...</div>
<!-- 响应式文字 -->
<p class="text-sm md:text-base lg:text-lg">响应式文字</p>
<!-- 暗色模式适配 -->
<div class="bg-gray-50 dark:bg-gray-900">
适配深色模式
</div>AI 编程中的 CSS 最佳实践
AI 生成 CSS 的常见问题与规避
/* 问题1:过度的 !important */
.bad {
color: red !important; /* AI 常用,但应该避免 */
font-size: 16px !important;
}
/* 解决:使用 Tailwind 的优先级机制或 CSS 级联层 */
@layer components {
.override-style {
/* 自然覆盖,无需 !important */
}
}
/* 问题2:固定像素值导致不响应 */
.bad {
width: 1200px; /* 不响应式 */
}
/* 解决:使用相对单位 */
.good {
max-width: 1200px;
width: 100%;
}
/* 问题3:忽略 CSS 变量 */
.bad {
color: #3b82f6; /* 硬编码颜色 */
}
/* 解决:使用设计 token */
.good {
color: var(--color-primary);
background: var(--color-surface);
}
/* 问题4:z-index 混乱 */
.bad {
z-index: 9999;
z-index: 10000;
}
/* 解决:建立 z-index 层级系统 */
:root {
--z-dropdown: 50;
--z-sticky: 100;
--z-modal: 200;
--z-toast: 300;
--z-tooltip: 400;
}主题系统设计
/* 轻量级主题切换 */
:root {
--bg-primary: #ffffff;
--bg-secondary: #f8fafc;
--text-primary: #0f172a;
--text-secondary: #475569;
--border: #e2e8f0;
--accent: #3b82f6;
}
[data-theme="dark"] {
--bg-primary: #0f172a;
--bg-secondary: #1e293b;
--text-primary: #f1f5f9;
--text-secondary: #94a3b8;
--border: #334155;
--accent: #60a5fa;
}
[data-theme="synthwave"] {
--bg-primary: #1a0a2e;
--bg-secondary: #2d1b4e;
--text-primary: #f5d0fe;
--text-secondary: #c084fc;
--border: #7c3aed;
--accent: #f472b6;
}
/* 应用主题变量 */
.page {
background: var(--bg-primary);
color: var(--text-primary);
}
.card {
background: var(--bg-secondary);
border: 1px solid var(--border);
}选型建议与性能优化
CSS 架构选型决策
| 项目规模 | 推荐方案 | 说明 |
|---|---|---|
| 个人项目 / 快速原型 | Tailwind CSS | 零配置,快速迭代 |
| 中小团队产品 | Tailwind + shadcn/ui | AI 友好,组件复用 |
| 大型企业系统 | CSS Modules + Design Tokens | 强类型,强隔离 |
| 设计系统开发 | CSS Custom Properties + Storybook | 可视化文档 |
| 设计还原优先 | 传统 CSS + BEM 命名 | 最大控制力 |
CSS 性能优化
/* 1. 避免样式计算复杂的选择器 */
/* 差:深度嵌套 */
.bad { }
.bad .parent .child .wrapper .content .text { }
/* 好:扁平化选择器 */
.good { }
/* 2. 使用 contain 属性隔离重排 */
.isolated {
contain: layout style paint; /* 完全隔离 */
contain: content; /* 仅内容隔离 */
}
/* 3. will-change 提示浏览器优化 */
.animated {
will-change: transform; /* 提前提升为独立图层 */
/* 注意:不要滥用,动画结束后移除 */
}
/* 4. 减少重绘重排 */
.efficient {
/* 使用 transform/opacity 而非 top/left 等属性做动画 */
transform: translateX(100px); /* GPU 加速 */
opacity: 0.5; /* GPU 加速 */
/* 避免: */
left: 100px; /* 触发重排 */
color: red; /* 触发重绘 */
}浏览器兼容性策略
/* 使用 @supports 检测 */
.feature {
/* 渐进增强 */
display: grid;
display: flex; /* 回退 */
}
@supports (container-type: inline-size) {
.card-container {
container-type: inline-size;
}
}
/* 使用 caniuse 查询兼容性 */
/* 2026年主流特性兼容性:*/
.grid { display: grid; } /* 97%+ */
.flexbox { display: flex; } /* 98%+ */
.custom-props { --var: 1; } /* 97%+ */
.has-selector { } /* 95%+ (IE不支持) */
.container-queries { container-type: size; } /* 87%+ */
.subgrid { grid-template-columns: subgrid; } /* 88%+ */SUCCESS
本文档系统性地介绍了 CSS 布局体系、盒模型、响应式策略、现代特性、动画运动、设计系统及 Tailwind CSS 深度指南。在 vibecoding 时代,推荐将 Tailwind CSS 作为主要样式工具,结合 shadcn/ui 组件库,可实现 AI 辅助开发的最高效率。
TIP
AI 编程中 CSS 的最佳实践:优先使用 Tailwind 的原子类来表达样式,减少 CSS 文件的创建;使用 CSS Custom Properties 构建主题系统;利用 Container Queries 实现真正的组件级响应式。
CSS 可访问性与包容性设计
语义化 HTML 与 ARIA
<!-- 语义化按钮 -->
<!-- 差:使用 div 模拟按钮 -->
<div class="btn" onclick="handleClick()">点击我</div>
<!-- 好:使用语义化按钮 -->
<button type="button" class="btn" onclick="handleClick()">点击我</button>
<!-- 需要链接行为时的无障碍方案 -->
<a href="/destination" class="btn" onclick="handleClick(event)">
点击我
</a>
<!-- 多个操作时的下拉菜单 -->
<div class="dropdown">
<button
type="button"
aria-haspopup="listbox"
aria-expanded="false"
aria-controls="dropdown-menu"
>
选项
<span aria-hidden="true">▼</span>
</button>
<ul
id="dropdown-menu"
role="listbox"
aria-label="可用选项"
hidden
>
<li role="option" aria-selected="true">选项 1</li>
<li role="option">选项 2</li>
<li role="option">选项 3</li>
</ul>
</div>焦点管理与键盘导航
/* 焦点样式 */
:focus {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* 可见焦点样式 */
:focus-visible {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* 移除默认焦点样式(需谨慎)*/
/* :focus:not(:focus-visible) { outline: none; } */
/* 跳过链接 */
.skip-link {
position: absolute;
top: -100%;
left: 16px;
padding: 12px 24px;
background: #3b82f6;
color: white;
text-decoration: none;
border-radius: 4px;
z-index: 1000;
}
.skip-link:focus {
top: 16px;
}
/* 模态框焦点陷阱 */
.modal-overlay {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgb(0 0 0 / 0.5);
}
.modal {
/* 当模态框打开时 */
/* 1. 将模态框设置为焦点 */
/* 2. 监听 Tab 键 */
/* 3. 当焦点到达最后一个元素时,跳回第一个元素 */
}
.modal:focus {
outline: none;
}
/* 焦点指示器 */
.accessible-focus {
/* 高对比度焦点样式 */
}
.accessible-focus:focus-visible {
outline: 3px solid currentColor;
outline-offset: 2px;
box-shadow: 0 0 0 6px rgb(59 130 246 / 0.3);
}颜色对比度
/* WCAG AA 标准 */
.text-normal {
/* 正常文本(<18px 或 <14px 粗体)需要 4.5:1 对比度 */
color: #1f2937; /* 灰色 800 */
background: #ffffff;
/* 对比度:12.63:1 ✓ */
}
.text-large {
/* 大文本(≥18px 或 ≥14px 粗体)需要 3:1 对比度 */
color: #6b7280; /* 灰色 500 */
background: #ffffff;
/* 对比度:5.88:1 ✓ */
}
.text-muted {
/* 辅助文本(≥14px)需要 3:1 对比度 */
color: #9ca3af; /* 灰色 400 */
background: #ffffff;
/* 对比度:2.73:1 ✗ 不合格 */
}
/* 使用 CSS 变量创建安全配色 */
:root {
--color-text: #1f2937; /* 12.63:1 */
--color-text-secondary: #4b5563; /* 7.54:1 */
--color-text-muted: #6b7280; /* 5.88:1 */
--color-primary: #3b82f6; /* 4.63:1 */
--color-primary-hover: #2563eb; /* 6.37:1 */
}
.button {
background: var(--color-primary);
color: white; /* 4.63:1 ✓ */
}
.button:hover {
background: var(--color-primary-hover);
color: white; /* 6.37:1 ✓ */
}动态内容可访问性
<!-- 实时更新区域 -->
<div
role="status"
aria-live="polite"
aria-atomic="true"
>
<!-- 使用 aria-live 通知屏幕阅读器 -->
<span id="status">{{ status }}</span>
</div>
<!-- 加载状态 -->
<div role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100">
加载中 75%
</div>
<!-- 错误提示 -->
<div role="alert" aria-live="assertive">
<p class="error">{{ errorMessage }}</p>
</div>
<!-- 表格可访问性 -->
<table role="grid" aria-label="数据表格">
<thead>
<tr>
<th scope="col" aria-sort="ascending">
<button type="button" aria-controls="data-table">
日期
<span aria-hidden="true">↑</span>
</button>
</th>
<th scope="col">金额</th>
</tr>
</thead>
<tbody>
<tr>
<td>2024-01-15</td>
<td>$100.00</td>
</tr>
</tbody>
</table>触摸与指针交互
/* 触摸友好的点击区域 */
.touch-target {
/* 最小触摸区域 44x44px (WCAG) */
min-width: 44px;
min-height: 44px;
padding: 12px 16px;
}
/* 悬停与触摸状态 */
@media (hover: hover) {
/* 有悬停能力的设备 */
.interactive:hover {
background: #f3f4f6;
}
}
@media (hover: none) {
/* 触摸设备 */
.interactive:active {
background: #e5e7eb;
}
}
/* 悬停时的手势提示 */
.touch-device .tooltip::before {
content: '长按查看详情';
position: absolute;
bottom: 100%;
}
/* 禁用状态 */
.disabled {
opacity: 0.5;
cursor: not-allowed;
pointer-events: none;
}
/* 长按菜单 */
.context-menu-trigger {
position: relative;
}
.context-menu {
position: absolute;
top: 100%;
left: 0;
min-width: 160px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 16px rgb(0 0 0 / 0.15);
z-index: 100;
}
/* PC 悬停,触摸长按 */
@media (hover: hover) {
.context-menu-trigger:hover .context-menu {
display: block;
}
}
@media (hover: none) and (pointer: coarse) {
/* 触摸设备 */
.context-menu {
display: none;
}
.context-menu-trigger:active .context-menu {
display: block;
}
}CSS 工具与调试
浏览器开发者工具
/* 使用开发者工具高亮布局 */
.highlight-layout {
/* 在开发者工具中可以看到 */
outline: 2px dashed red; /* Flex/Grid 容器 */
outline-offset: 2px;
background: rgb(255 0 0 / 0.1);
}
/* Grid 调试 */
.debug-grid {
display: grid;
outline: 1px solid rgba(255, 0, 0, 0.3);
background-image:
linear-gradient(rgba(255, 0, 0, 0.05) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 0, 0, 0.05) 1px, transparent 1px);
background-size: 20px 20px;
}
/* Flex 调试 */
.debug-flex {
display: flex;
outline: 1px solid rgba(0, 0, 255, 0.3);
}
.debug-flex > * {
outline: 1px dashed rgba(0, 0, 255, 0.3);
background: rgba(0, 0, 255, 0.05);
}
/* 间距可视化 */
.debug-spacing > * + * {
position: relative;
}
.debug-spacing > * + *::before {
content: '';
position: absolute;
top: -8px;
left: 0;
right: 0;
height: 8px;
background: rgba(0, 255, 0, 0.2);
}PostCSS 与预处理
// postcss.config.js
export default {
plugins: {
// 自动添加前缀
'autoprefixer': {},
// CSS 模块
'postcss-modules': {},
// CSS Nesting
'postcss-nesting': {},
// 自定义属性转换
'postcss-custom-properties': {
preserve: true,
},
// 压缩
'cssnano': {},
},
};/* PostCSS 嵌套语法 */
.card {
padding: 20px;
background: white;
border-radius: 12px;
/* 嵌套 */
&__header {
display: flex;
align-items: center;
justify-content: space-between;
}
&__title {
font-size: 18px;
font-weight: 600;
margin: 0;
}
&__content {
margin-top: 16px;
}
/* 伪类嵌套 */
&:hover {
box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
}
/* 媒体查询嵌套 */
@media (max-width: 768px) {
padding: 16px;
&__title {
font-size: 16px;
}
}
}CSS Linting
// stylelint.config.js
export default {
extends: [
'stylelint-config-standard',
'stylelint-config-recessed',
],
rules: {
// 颜色格式
'color-hex-length': 'short',
'color-named': 'never',
// 格式
'indentation': 2,
'value-keyword-case': 'lower',
'selector-class-pattern': '^[a-z][a-zA-Z0-9]*(-[a-z][a-zA-Z0-9]*)*$',
'selector-id-pattern': '^[a-z][a-zA-Z0-9]*(-[a-z][a-zA-Z0-9]*)*$',
// 禁止
'no-descending-specificity': null,
'no-invalid-double-slash-comments': true,
// 字体
'font-family-no-missing-generic-family-keyword': true,
// 值
'value-no-vendor-prefix': true,
},
overrides: [
{
files: ['*.module.css'],
rules: {
'selector-class-pattern': '^[a-z][a-zA-Z0-9]*(_[a-z][a-zA-Z0-9]*)*$',
},
},
],
};CSS 架构模式
ITCSS 架构
/* ITCSS: Inverted Triangle CSS */
/* 按特异性从低到高排列 */
/* 1. Settings - 变量定义 */
:root {
--color-primary: #3b82f6;
--font-size-base: 16px;
--spacing-unit: 8px;
}
/* 2. Tools - Mixins 和 Functions */
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
/* 3. Generic - 重置和 normalize */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* 4. Elements - 基础元素样式 */
h1 {
font-size: 2rem;
margin: 0 0 1rem;
}
/* 5. Objects - 可复用结构类 */
.o-flex {
display: flex;
}
.o-container {
max-width: 1200px;
margin: 0 auto;
padding: 0 var(--spacing-unit);
}
/* 6. Components - 组件样式 */
.c-button {
padding: 12px 24px;
background: var(--color-primary);
border: none;
border-radius: 8px;
color: white;
}
/* 7. Utilities - 覆盖其他一切的实用类 */
.u-text-center { text-align: center; }
.u-hidden { display: none; }
.u-float-right { float: right; }BEM 命名规范
/* BEM: Block Element Modifier */
/* Block */
.card { }
/* Element (属于 Block) */
.card__header { }
.card__body { }
.card__footer { }
.card__title { }
.card__image { }
.card__button { }
/* Modifier (改变 Block 或 Element 的样式) */
.card--featured { }
.card__button--primary { }
.card__button--secondary { }
.card--disabled { }
/* 嵌套示例 */
.card {
/* Block 样式 */
}
.card__header {
/* Element 样式 */
}
.card__title {
font-size: 18px;
}
.card__title--large {
/* Modifier on Element */
font-size: 24px;
}
/* 避免过度嵌套,通常最多 2 层 */
.article-card {
/* 第一层 */
}
.article-card__header {
/* 第二层 */
}
/* 不要这样 */
/* .article-card__header__title__text */Utility-First 模式(Tailwind)
<!-- 原子化类名组合 -->
<div class="flex items-center justify-between p-4 bg-white rounded-lg shadow-md">
<h2 class="text-lg font-semibold text-gray-900">标题</h2>
<button class="px-4 py-2 text-sm font-medium text-white bg-blue-500 rounded-md hover:bg-blue-600 transition-colors">
操作
</button>
</div>
<!-- 响应式前缀 -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<!-- 移动端 1 列,平板 2 列,桌面 3 列 -->
</div>
<!-- 状态变体 -->
<button class="bg-blue-500 hover:bg-blue-600 active:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed">
按钮
</button>
<!-- 暗色模式 -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
自适应内容
</div>
<!-- 组合使用 -->
<button class="
px-4 py-2
bg-blue-500 hover:bg-blue-600
text-white font-medium
rounded-lg shadow-sm
transition-colors duration-200
focus:outline-none focus:ring-2 focus:ring-blue-300 focus:ring-offset-2
">
按钮
</button>CSS 未来趋势与新特性
近期提案
/* 1. @layer 规则(已支持)*/
/* 已广泛支持,用于控制级联顺序 */
@layer reset, base, components, utilities;
@layer reset {
* { margin: 0; }
}
@layer base {
body { font-family: system-ui; }
}
@layer components {
.btn { padding: 12px 24px; }
}
@layer utilities {
.hidden { display: none !important; }
}
/* 2. :has() 父选择器(已支持)*/
/* 已在主流浏览器支持 */
form:has(:invalid) {
border-color: red;
}
.card:has(.badge) {
padding-top: 24px;
}
/* 3. @scope 作用域(即将支持)*/
@scope (.card) {
:scope {
padding: 16px;
}
.title {
font-size: 18px;
}
}
/* 4. 容器查询(已支持)*/
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
}
}
/* 5. 颜色函数(已支持)*/
.button {
background: light-dark(white, black);
color: light-dark(black, white);
}
.button:hover {
background: color-mix(in oklch, var(--primary) 80%, white);
}
/* 6. 嵌套规则(已支持)*/
.nested {
color: red;
&:hover {
color: blue;
}
& > .child {
color: green;
}
}新兴 CSS 特性
/* 1. View Transitions API */
@view-transition {
navigation: auto;
}
::view-transition-old(root) {
animation: fade-out 200ms ease-out;
}
::view-transition-new(root) {
animation: fade-in 200ms ease-in;
}
/* 命名视图过渡 */
.hero-image {
view-transition-name: hero;
}
::view-transition-old(hero) {
animation: scale-down 200ms ease-out;
}
::view-transition-new(hero) {
animation: scale-up 200ms ease-in;
}
/* 2. 触觉反馈(实验性)*/
.interactive {
/* 未来可能支持的 API */
/* @property --haptic-intensity; */
}
/* 3. 色彩空间扩展 */
.advanced-color {
/* LCH 色彩空间 */
color: lch(58% 32 240);
/* OKLCH(感知均匀)*/
color: oklch(70% 0.15 250);
/* P3 广色域 */
color: color(display-p3 0.8 0.2 0.1);
}
/* 4. 混合模式 */
.blend {
background-blend-mode: multiply;
mix-blend-mode: screen;
}
/* 5. 滚动驱动动画 */
@keyframes slide-in {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
.scrollable-list {
animation: slide-in linear;
animation-timeline: scroll(root);
}
/* 6. CSS Anchor Positioning */
.popover {
position-anchor: --trigger-button;
position: absolute;
position: auto;
top: anchor(bottom);
left: anchor(center);
}CSS 性能与最佳实践
渲染性能优化
/* 1. 使用 GPU 加速的属性 */
.gpu-accelerated {
/* 这些属性会创建 GPU 层 */
transform: translateZ(0);
transform: translate3d(0, 0, 0);
will-change: transform, opacity;
/* 更好的方式:明确声明 */
will-change: transform;
}
/* 2. 避免触发布局的属性 */
.avoid-layout {
/* 避免使用这些属性做动画 */
/* width, height, padding, margin */
/* top, left, right, bottom */
/* border-width */
/* 使用这些属性代替 */
transform: translate();
opacity: 0;
filter: blur();
}
/* 3. contain 属性 */
.contained {
/* layout: 内部布局不影响外部 */
/* style: 样式计算隔离 */
/* paint: 内部绘制不影响外部 */
contain: layout style paint;
/* 组合 */
contain: content; /* layout style paint */
contain: strict; /* layout style paint size */
}
/* 4. 减少重绘重排 */
.efficient {
/* 使用 transform/opacity 做动画 */
transform: scale(1.05);
opacity: 0.8;
}
/* 不好:触发布局 */
.inefficient {
width: 110%;
margin-left: 10%;
padding: 20px;
}CSS 加载优化
<!-- 关键 CSS 内联 -->
<style>
.critical { color: red; }
</style>
<!-- 非关键 CSS 异步加载 -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
<!-- 或使用 CSS Containment -->
<!-- 现代浏览器支持 --><!-- 媒体查询加载 -->
<link rel="stylesheet" href="mobile.css" media="screen and (max-width: 600px)">
<link rel="stylesheet" href="desktop.css" media="screen and (min-width: 601px)">
<!-- 打印样式 -->
<link rel="stylesheet" href="print.css" media="print">构建优化
// 使用 PurgeCSS 移除未使用 CSS
// postcss.config.js
import purgecss from '@fullhuman/postcss-purgecss';
export default {
plugins: [
purgecss({
content: ['./src/**/*.html', './src/**/*.js', './src/**/*.vue'],
safelist: ['active', 'disabled', 'loading'],
}),
],
};
// 使用 cssnano 压缩
import cssnano from 'cssnano';
export default {
plugins: [
cssnano({
preset: [
'default',
{
discardComments: { removeAll: true },
normalizeWhitespace: true,
},
],
}),
],
};CSS 资源与学习
官方资源
| 资源 | 链接 |
|---|---|
| MDN CSS 文档 | https://developer.mozilla.org/zh-CN/docs/Web/CSS |
| CSS 工作组规范 | https://www.w3.org/Style/CSS/ |
| Can I Use | https://caniuse.com/ |
| CSS Tricks | https://css-tricks.com/ |
学习工具
| 工具 | 描述 |
|---|---|
| Flexbox Froggy | Flexbox 互动学习游戏 |
| Grid Garden | Grid 布局互动学习游戏 |
| CSS Battle | CSS 代码挑战 |
| Codrops | CSS 技术教程 |
工具库
| 库 | 描述 |
|---|---|
| Tailwind CSS | 实用优先 CSS 框架 |
| UnoCSS | 即时原子化 CSS 引擎 |
| Vanilla Extract | 类型安全 CSS-in-TypeScript |
| Panda CSS | CSS-in-JS 替代方案 |
| Styled Components | React CSS-in-JS |
CSS 与设计体系总结
核心要点回顾
/* 布局决策指南 */
.layout-decision {
/* 单行/单列 → Flexbox */
display: flex;
flex-direction: row;
/* 页面级布局 → Grid */
display: grid;
grid-template-areas:
"header"
"main"
"footer";
/* 响应式组件 → Container Queries */
container-type: inline-size;
}
/* 主题系统 */
.theme-system {
/* 使用 CSS 变量定义设计 token */
--color-primary: #3b82f6;
--spacing-unit: 8px;
--radius-base: 8px;
/* 语义化映射 */
--color-action: var(--color-primary);
--color-text-primary: var(--color-gray-900);
/* 组件级变量 */
--button-bg: var(--color-action);
--button-radius: var(--radius-base);
}
/* 可访问性 */
.accessible {
/* 颜色对比度 */
color: #1f2937;
background: white; /* 12.6:1 ✓ */
/* 焦点可见 */
:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
/* 尊重用户偏好 */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
}相关资源
| 资源 | 链接 |
|---|---|
| Flexbox 与 Grid 布局 | 09-CSS与设计体系/Flexbox与Grid.md |
| Tailwind CSS 深度指南 | 08-样式与CSS/TailwindCSS深度指南.md |
| 设计系统架构 | 08-样式与CSS/设计系统架构.md |
| 动画与运动设计 | 08-样式与CSS/动画与运动设计.md |
本文档由 归愚知识系统 自动生成
CSS 工程化实践
PostCSS 配置与应用
PostCSS 是现代 CSS 工具链的核心,它将 CSS 解析为 AST 并通过插件进行处理:
// postcss.config.js
module.exports = {
plugins: [
// 1. 样式重置
'postcss-normalize', // 现代 CSS 重置
// 2. 嵌套语法
['postcss-nested', {
'bubble PreludeList': true, // 嵌套 @media
}],
// 3. 自动前缀
['autoprefixer', {
grid: 'autoplace', // 自动为 Grid 添加前缀
flexbox: 'no-2009', // 只为最新 flexbox 添加前缀
}],
// 4. CSS Modules(可选)
// ['postcss-modules', {
// generateScopedName: '[name]__[local]___[hash:base64:5]',
// }],
// 5. CSS-in-JS 样式提取
// 'postcss-styled-components',
// 6. 变量定义
['postcss-custom-media', {
extensions: {
'--mobile': '(max-width: 639px)',
'--tablet': '(min-width: 640px) and (max-width: 1023px)',
'--desktop': '(min-width: 1024px)',
},
}],
// 7. 颜色函数
'postcss-color-mod-function',
// 8. 媒体查询排序
['postcss-sort-media-queries', {
sort: 'mobile-first', // 移动优先排序
}],
// 9. 压缩
...(process.env.NODE_ENV === 'production' ? [
['cssnano', {
preset: 'default',
}],
] : []),
],
}Sass/SCSS 深度应用
// Sass 高级特性
// 1. 混入(Mixins)
@mixin respond-to($breakpoint) {
@if $breakpoint == 'mobile' {
@media (max-width: 639px) { @content; }
} @else if $breakpoint == 'tablet' {
@media (min-width: 640px) and (max-width: 1023px) { @content; }
} @else if $breakpoint == 'desktop' {
@media (min-width: 1024px) { @content; }
}
}
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@mixin truncate($lines: 1) {
@if $lines == 1 {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
} @else {
display: -webkit-box;
-webkit-line-clamp: $lines;
-webkit-box-orient: vertical;
overflow: hidden;
}
}
@mixin button-variant($bg, $color, $hover-bg) {
background: $bg;
color: $color;
&:hover {
background: $hover-bg;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
// 使用混入
.button {
@include flex-center;
padding: 12px 24px;
border-radius: 8px;
&-primary {
@include button-variant(#3b82f6, white, #2563eb);
}
&-secondary {
@include button-variant(#f3f4f6, #1f2937, #e5e7eb);
}
}
// 2. 函数
@function rem($px) {
@return calc($px / 16) * 1rem;
}
@function color-contrast($color) {
$luminance: 0.299 * red($color) + 0.587 * green($color) + 0.114 * blue($color);
@return if($luminance > 149, #000000, #ffffff);
}
@function spacing($key) {
$spacing: (
'xs': 4px,
'sm': 8px,
'md': 16px,
'lg': 24px,
'xl': 32px,
);
@return map-get($spacing, $key);
}
// 使用函数
.container {
padding: rem(16);
margin-top: spacing('lg');
}
// 3. 占位符(Placeholders)
%button-base {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 12px 24px;
font-weight: 600;
border-radius: 8px;
cursor: pointer;
transition: all 200ms ease;
}
%button-primary {
@extend %button-base;
background: #3b82f6;
color: white;
}
%button-secondary {
@extend %button-base;
background: #f3f4f6;
color: #1f2937;
}
.primary-btn {
@extend %button-primary;
}
.secondary-btn {
@extend %button-secondary;
}
// 4. 控制流
$theme: 'dark';
.card {
@if $theme == 'dark' {
background: #1f2937;
color: white;
} @else if $theme == 'light' {
background: white;
color: #1f2937;
} @else {
background: inherit;
}
}
// 循环生成
$colors: (
'primary': #3b82f6,
'secondary': #8b5cf6,
'success': #10b981,
'warning': #f59e0b,
'danger': #ef4444,
);
@each $name, $color in $colors {
.bg-#{$name} {
background: $color;
}
.text-#{$name} {
color: $color;
}
.btn-#{$name} {
background: $color;
color: color-contrast($color);
&:hover {
background: darken($color, 10%);
}
}
}Stylelint 代码检查
// .stylelintrc.json
{
"extends": [
"stylelint-config-standard",
"stylelint-config-recess-order", // 属性排序
"stylelint-config-prettier" // 与 Prettier 兼容
],
"plugins": [
"stylelint-scss",
"stylelint-order"
],
"rules": {
// 颜色
"color-no-invalid-hex": true,
"color-hex-length": "short",
"color-named": "never",
// 选择器
"selector-max-id": 0,
"selector-max-compound-selectors": 4,
"selector-max-type": [2, { "ignore": ["child", "descendant"] }],
"selector-no-vendor-prefix": true,
// 属性
"property-no-vendor-prefix": true,
"value-no-vendor-prefix": true,
// 单位
"unit-no-unknown": true,
"unit-allowed-list": ["px", "em", "rem", "%", "vh", "vw", "vmin", "vmax", "s", "ms"],
// 函数
"function-url-quotes": "always",
// 声明
"declaration-no-important": true,
"declaration-block-single-line-max-declarations": 1,
// 块
"block-no-empty": true,
// 空格
"indentation": 2,
"no-eol-whitespace": true,
// 注释
"comment-empty-line-before": ["always", {
"except": ["first-nested"],
"ignore": ["after-comment", "inside-block"]
}],
// SCSS 特定
"scss/dollar-variable-pattern": "^[a-z]+-[a-z]+(-[a-z]+)*$",
"scss/at-extend-no-missing-placeholder": true,
"scss/at-mixin-pattern": "^[a-z]+-[a-z]+(-[a-z]+)*$",
// 属性排序
"order/properties-order": [
"position",
"top",
"right",
"bottom",
"left",
"z-index",
"display",
"flexbox",
"grid",
"float",
"width",
"height",
"margin",
"padding",
"border",
"background",
"color",
"font",
"animation",
"transition",
"transform",
"opacity",
]
}
}可访问性设计
ARIA 属性应用
/* ARIA 属性与样式联动 */
/* 1. 焦点状态 */
.button:focus {
outline: none;
}
.button:focus-visible {
box-shadow: 0 0 0 3px #3b82f6;
outline: 2px solid transparent;
}
/* 2. 隐藏内容但保持可访问 */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
white-space: normal;
}
/* 3. 展开/收起状态 */
[aria-expanded="true"] .icon {
transform: rotate(180deg);
}
[aria-expanded="false"] .icon {
transform: rotate(0);
}
/* 4. 选中状态 */
[aria-checked="true"] .checkbox {
background: #3b82f6;
border-color: #3b82f6;
}
[aria-selected="true"] .tab {
border-bottom: 2px solid #3b82f6;
color: #3b82f6;
}
/* 5. 加载状态 */
[aria-busy="true"] {
opacity: 0.7;
pointer-events: none;
}
/* 6. 禁用状态 */
[aria-disabled="true"] {
opacity: 0.5;
cursor: not-allowed;
}颜色对比度
/* WCAG 对比度要求 */
/* AAA 级(7:1 比率) */
.text-primary {
color: #1f2937; /* 深色文本在白色背景 */
background: #ffffff;
}
/* AA 级(4.5:1 比率) */
.text-secondary {
color: #4b5563; /* 灰色文本在白色背景 */
background: #ffffff;
}
/* 大文本 AA 级(3:1 比率) */
.heading-large {
color: #6b7280; /* 18px+ 或 14px bold */
background: #ffffff;
}
/* 深色背景上的浅色文本 */
.dark-bg {
background: #1f2937;
color: #f9fafb; /* AAA 级 */
}
/* 计算工具函数 */
:root {
--color-bg: #ffffff;
--color-text: #1f2937;
/* 动态计算对比度 */
--contrast-ratio: calc(
(max(luminance(--color-bg), luminance(--color-text)) + 0.05) /
(min(luminance(--color-bg), luminance(--color-text)) + 0.05)
);
}
/* 焦点指示器 */
:focus-visible {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* 高对比度模式支持 */
@media (prefers-contrast: high) {
:root {
--color-border: #000000;
--color-text: #000000;
--color-bg: #ffffff;
}
.button {
border: 2px solid currentColor;
}
}键盘导航支持
/* 键盘导航样式 */
/* 1. 跳转链接 */
.skip-link {
position: absolute;
top: -100%;
left: 16px;
padding: 12px 24px;
background: #3b82f6;
color: white;
text-decoration: none;
border-radius: 8px;
z-index: 9999;
transition: top 200ms ease;
}
.skip-link:focus {
top: 16px;
}
/* 2. Tab 焦点指示 */
[tabindex="0"]:focus-visible {
box-shadow: 0 0 0 2px #3b82f6;
}
/* 3. 链接下划线 */
a {
text-decoration: underline;
text-underline-offset: 2px;
}
a:focus-visible {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* 4. 下拉菜单 */
.menu-item {
position: relative;
}
.menu-item[aria-expanded="true"] > .submenu {
display: block;
}
.submenu {
display: none;
position: absolute;
top: 100%;
left: 0;
}
/* 5. 模态框 */
.modal[aria-hidden="true"] {
display: none;
}
.modal {
display: flex;
align-items: center;
justify-content: center;
}
.modal:focus {
outline: none;
}
.modal-content {
outline: none;
}
/* 6. 拖拽区域 */
.drop-zone {
outline: 2px dashed transparent;
transition: outline-color 200ms ease;
}
.drop-zone:focus-within,
.drop-zone.drag-over {
outline-color: #3b82f6;
}CSS 性能优化
渲染性能
/* 渲染性能优化 */
/* 1. 避免触发布局的操作 */
.bad {
/* 读取 layout 属性后写入 */
element.style.width = element.offsetWidth + 10 + 'px';
/* 连续修改多个属性 */
element.style.width = '100px';
element.style.height = '100px';
element.style.margin = '10px';
}
.good {
/* 使用 CSS 类统一修改 */
element.classList.add('expanded');
/* 使用 CSS 变量批量更新 */
element.style.setProperty('--size', '100px');
}
/* 2. 使用 transform 和 opacity */
.bad {
/* 触发布局 */
position: absolute;
left: 100px;
top: 100px;
}
.good {
/* 只触发合成 */
transform: translate(100px, 100px);
opacity: 0.8;
}
/* 3. will-change 提示 */
.animated-element {
will-change: transform, opacity;
/* 动画开始前添加,结束后移除 */
}
/* 4. 避免过深的选择器 */
.bad {
.parent .child .wrapper .content .text {
color: red;
}
}
.good {
.content-text {
color: red;
}
}
/* 5. 使用 contain 隔离 */
.isolated-component {
contain: layout style paint;
/* 组件内部变化不会影响外部 */
}
/* 6. 减少重绘 */
.bad {
.hover-effect:hover {
background-color: blue;
color: white;
border-color: blue;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
}
.good {
.hover-effect {
transition: all 200ms ease;
}
.hover-effect:hover {
/* 浏览器可以批量处理 */
}
}动画性能
/* 动画性能最佳实践 */
/* 1. 使用 GPU 加速 */
.gpu-accelerated {
transform: translateZ(0);
/* 或 */
transform: translate3d(0, 0, 0);
}
/* 2. 优先使用 transform 和 opacity */
@keyframes animate {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 3. 使用 FLIP 技术 */
.flip-container {
position: relative;
height: 100px;
}
.flip-item {
position: absolute;
transition: transform 300ms ease;
}
/* 4. 动画防抖 */
@keyframes debounced-animation {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.05);
}
}
.debounced {
animation: debounced-animation 300ms ease;
animation-play-state: paused;
}
.debounced.ready {
animation-play-state: running;
}
/* 5. 减少动画复杂性 */
.bad {
/* 同时动画多个属性 */
transition:
width 300ms ease,
height 300ms ease,
margin 300ms ease,
padding 300ms ease,
color 300ms ease,
background-color 300ms ease;
}
.good {
/* 分离动画 */
.container {
transition: width 300ms ease, height 300ms ease;
}
.inner {
transition: color 200ms ease, background-color 200ms ease;
}
}
/* 6. 使用 requestAnimationFrame */
.js-animation {
/* 通过 JavaScript 控制 */
}CSS 加载优化
/* 加载性能优化 */
/* 1. 关键 CSS 内联 */
<style>
.critical-header { display: flex; }
.critical-hero { min-height: 80vh; }
</style>
/* 2. 异步加载非关键 CSS */
<link rel="preload" href="styles.css" as="style"
onload="this.onload=null;this.rel='stylesheet'">
/* 3. 使用 content-visibility */
.lazy-section {
content-visibility: auto;
contain-intrinsic-size: 0 500px;
/* 视口外不渲染 */
}
/* 4. 预加载字体 */
@font-face {
font-display: swap;
/* swap: 显示后备字体,等字体加载后交换 */
}
/* 5. 字体子集化 */
@font-face {
font-family: 'CustomFont';
src: url('font-latin.woff2') format('woff2');
unicode-range: U+0000-00FF;
}
/* 6. 图片加载优化 */
img {
loading: lazy;
decoding: async;
}
.above-fold {
loading: eager;
decoding: sync;
}现代 CSS 新特性
@layer 级联层
/* @layer 级联层详解 */
/*
* 级联层优先级(后声明的层优先级更高):
* @layer reset < @layer base < @layer components < @layer utilities
*/
/* 定义层顺序(只在第一次定义时生效)*/
@layer reset, base, components, theme, utilities, overrides;
/* 重置层 */
@layer reset {
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
}
/* 基础层 */
@layer base {
html {
font-size: 16px;
-webkit-font-smoothing: antialiased;
}
body {
font-family: system-ui, sans-serif;
line-height: 1.5;
}
}
/* 组件层 */
@layer components {
.button {
display: inline-flex;
padding: 12px 24px;
border-radius: 8px;
font-weight: 600;
cursor: pointer;
transition: all 200ms ease;
}
.card {
background: white;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
}
/* 主题层 */
@layer theme {
:root {
--primary: #3b82f6;
--secondary: #8b5cf6;
}
}
/* 工具类层 */
@layer utilities {
.hidden { display: none !important; }
.flex { display: flex; }
.grid { display: grid; }
}
/* 覆盖层 */
@layer overrides {
.button {
background: var(--primary) !important;
}
}
/* 匿名层(无法从外部添加样式)*/
@layer {
.temporary-styles {
background: red;
}
}
/* 嵌套层 */
@layer components {
@layer cards {
.card { border-radius: 16px; }
}
@layer buttons {
.button { font-size: 14px; }
}
}:has() 父选择器
/* :has() 选择器详解 */
/* 1. 基本用法 */
article:has(img) {
/* article 包含 img 时应用样式 */
}
form:has(:invalid) {
border-color: red;
}
/* 2. 表单验证 */
input:not(:placeholder-shown):invalid {
border-color: red;
}
form:has(input:invalid) .submit-btn {
opacity: 0.5;
pointer-events: none;
}
/* 3. 列表状态 */
ul:has(li.active) .badge {
display: inline-block;
}
ul:empty {
display: none;
}
/* 4. 复选框状态 */
label:has(input[type="checkbox"]:checked) {
background: #dbeafe;
}
label:has(input[type="checkbox"]:indeterminate) {
background: #fef3c7;
}
/* 5. 拖拽状态 */
.card-container:has(.card.dragging) {
background: #f3f4f6;
}
/* 6. 响应式切换 */
.container:has(.sidebar) {
grid-template-columns: 250px 1fr;
}
/* 7. 计数器 */
.list:has(li:nth-child(10)) .counter {
background: #ef4444;
}
/* 8. 模式匹配 */
.button:has(.icon) {
gap: 8px;
}
.button:not(:has(.icon)) {
padding: 10px 16px;
}
/* 9. 复杂选择 */
.card:has(.badge):has(.image) {
/* 同时包含 badge 和 image 的 card */
}
/* 10. 否定组合 */
.card:not(:has(.badge)) {
padding: 20px;
}颜色函数进阶
/* 颜色函数详解 */
/* 1. color-mix() 混合颜色 */
.mixed-50 {
background: color-mix(in srgb, #3b82f6 50%, #ffffff);
}
.mixed-30 {
background: color-mix(in srgb, #3b82f6 30%, #000000);
}
/* 2. 相对颜色语法 */
:root {
--base: #3b82f6;
--lighter: oklch(
from var(--base)
calc(l + 0.15)
c
h
);
--darker: oklch(
from var(--base)
calc(l - 0.15)
c
h
);
--more-saturated: oklch(
from var(--base)
l
calc(c * 1.5)
h
);
--hue-shifted: oklch(
from var(--base)
l
c
calc(h + 30)
);
}
/* 3. OKLCH 色彩空间 */
.oklch-colors {
--blue: oklch(59% 0.15 250);
--green: oklch(59% 0.15 150);
--red: oklch(59% 0.15 25);
/* 相同亮度,不同色相 */
background: var(--blue);
}
/* 4. lab() 色彩空间 */
.lab-colors {
--color: lab(60% 50 40);
}
/* 5. lch() 色彩空间 */
.lch-colors {
--color: lch(60% 80 250);
}
/* 6. hwb() 色彩空间 */
.hwb-colors {
--color: hwb(250 0% 50%);
}
/* 7. color() 函数 */
.colors {
--display-p3: color(display-p3 0.8 0.2 0.1);
--rec2020: color(rec2020 0.3 0.8 0.2);
}
/* 8. 渐变中的颜色函数 */
.gradient {
background: linear-gradient(
to right,
oklch(70% 0.15 250),
oklch(70% 0.15 350)
);
}@property 自定义属性
/* @property 自定义属性详解 */
/* 定义可动画的 CSS 变量 */
@property --gradient-angle {
syntax: '<angle>';
inherits: false;
initial-value: 0deg;
}
@property --progress {
syntax: '<percentage>';
inherits: false;
initial-value: 0%;
}
@property --color-stop {
syntax: '<color>';
inherits: false;
initial-value: #3b82f6;
}
/* 1. 旋转动画 */
.rotating {
--gradient-angle: 0deg;
background: conic-gradient(
from var(--gradient-angle),
#3b82f6,
#8b5cf6,
#ec4899,
#3b82f6
);
animation: rotate 3s linear infinite;
}
@keyframes rotate {
to {
--gradient-angle: 360deg;
}
}
/* 2. 进度条动画 */
.progress {
--progress: 0%;
width: var(--progress);
transition: --progress 300ms ease;
}
.progress.loaded {
--progress: 100%;
}
/* 3. 颜色渐变动画 */
.color-transition {
--color-stop: #3b82f6;
background: var(--color-stop);
transition: --color-stop 500ms ease;
}
.color-transition:hover {
--color-stop: #ec4899;
}
/* 4. 复杂动画 */
.complex {
--angle: 0deg;
--scale: 1;
--hue: 0;
transform: rotate(var(--angle)) scale(var(--scale));
filter: hue-rotate(var(--hue));
animation: complex-animation 5s ease infinite;
}
@keyframes complex-animation {
0% {
--angle: 0deg;
--scale: 1;
--hue: 0;
}
50% {
--angle: 180deg;
--scale: 1.2;
--hue: 180;
}
100% {
--angle: 360deg;
--scale: 1;
--hue: 360;
}
}AI 辅助 CSS 开发
提示工程模板
// AI CSS 提示模板
const cssPrompts = {
// 基础组件生成
generateComponent: `
生成一个 {componentName} 组件的样式。
技术栈:{techStack}
设计系统:{designSystem}
要求:
- 响应式设计
- 支持暗色模式
- 符合无障碍标准
- 使用 CSS 变量管理主题
`,
// 布局生成
generateLayout: `
生成一个 {layoutType} 布局。
技术栈:{techStack}
要求:
- 使用 {layoutTool}(Grid/Flexbox)
- 响应式断点:{breakpoints}
- 移动优先
- {additionalRequirements}
`,
// 动画生成
generateAnimation: `
生成一个 {animationType} 动画。
场景:{useCase}
要求:
- 性能优化(60fps)
- 支持 prefers-reduced-motion
- 符合 {animationLibrary} 规范
- 持续时间:{duration}
`,
// 主题生成
generateTheme: `
生成一个 {themeType} 主题的 CSS 变量定义。
配色方案:{colorScheme}
要求:
- 使用 OKLCH 色彩空间
- 支持暗色模式
- 语义化变量命名
- {additionalRequirements}
`,
// 代码审查
reviewCSS: `
审查以下 CSS 代码:
{cssCode}
检查项:
- 性能问题
- 可访问性问题
- 浏览器兼容性
- 最佳实践
- 重构建议
`,
};
// 使用示例
async function generateComponent(name, context) {
const prompt = cssPrompts.generateComponent
.replace('{componentName}', name)
.replace('{techStack}', 'React + Tailwind')
.replace('{designSystem}', 'shadcn/ui');
const response = await ai.generate(prompt);
return response;
}AI 代码模式
// AI 辅助 CSS 开发的最佳模式
const cssPatterns = {
// 1. 响应式卡片模式
responsiveCard: (data) => `
<div class="card ${data.variant ? `card--${data.variant}` : ''}">
${data.image ? `<div class="card__image"><img src="${data.image}" alt="" /></div>` : ''}
<div class="card__content">
${data.title ? `<h3 class="card__title">${data.title}</h3>` : ''}
${data.description ? `<p class="card__description">${data.description}</p>` : ''}
${data.actions ? `<div class="card__actions">${data.actions}</div>` : ''}
</div>
</div>
`,
// 2. Tailwind 组件生成
tailwindComponent: (name, props) => `
function ${name}({ ${props.join(', ')} }) {
return (
<div class="flex items-center justify-between p-6 bg-white rounded-xl shadow-md hover:shadow-lg transition-shadow duration-300">
{/* Component content */}
</div>
);
}
`,
// 3. CSS 变量主题
themeVariables: (colors) => `
:root {
${Object.entries(colors.light).map(([key, value]) =>
`--color-${key}: ${value};`
).join('\n ')}
}
[data-theme="dark"] {
${Object.entries(colors.dark).map(([key, value]) =>
`--color-${key}: ${value};`
).join('\n ')}
}
`,
};代码质量检查清单
// AI 生成代码的质量检查
const cssChecklist = {
// 1. 基础检查
basics: [
'使用语义化的类名',
'避免 !important(除非必要)',
'避免行内样式',
'使用 CSS 变量而非硬编码值',
'遵循 BEM/ITCSS 等命名规范',
],
// 2. 响应式检查
responsive: [
'使用移动优先媒体查询',
'使用相对单位(rem/em/vw)而非固定像素',
'测试所有断点',
'考虑触摸设备',
'使用容器查询(Container Queries)',
],
// 3. 性能检查
performance: [
'使用 transform/opacity 而非触发布局的属性',
'避免过深的嵌套选择器',
'使用 will-change 优化动画元素',
'考虑 content-visibility 优化长页面',
'使用 contain 隔离组件',
],
// 4. 可访问性检查
a11y: [
'检查颜色对比度(4.5:1)',
'确保焦点状态可见',
'支持 prefers-reduced-motion',
'ARIA 属性正确使用',
'屏幕阅读器内容可访问',
],
// 5. 维护性检查
maintainability: [
'遵循 DRY 原则',
'使用设计系统 Token',
'组件样式独立',
'文档注释(复杂逻辑)',
'版本兼容性考虑',
],
};SUMMARY
CSS 现代开发已经从「写样式」演进为「系统工程」。掌握 CSS 布局(Flexbox/Grid)、现代特性(Custom Properties/Container Queries/:has())、动画系统、设计系统(Design Tokens)以及工程化工具(PostCSS/Sass/Stylelint)是现代前端工程师的必备技能。在 AI 时代,善用 AI 辅助生成和维护 CSS,同时保持对代码质量的把控,是提升开发效率的关键。
本文档由 归愚知识系统 自动生成