CSS相关

30 minute read

CSS 前端开发 完整系统学习大纲


一、CSS 基础与核心概念

1.1 CSS 发展历史

  • 1994年:Håkon Wium Lie 提出CSS概念
  • 1996年:CSS1 发布,提供基本样式控制
  • 1998年:CSS2 发布,新增定位、媒体类型等
  • 2011年:CSS2.1 成为W3C推荐标准
  • 2012年:CSS3 模块化开始,分模块发布
  • 至今:CSS4 部分特性草案,持续演进

1.2 CSS 核心特性

  • 层叠性:多个样式规则作用于同一元素,按优先级应用
  • 继承性:子元素继承父元素的某些样式
  • 优先级:选择器权重决定哪个样式生效
  • 模块化:CSS3 按功能分模块,可独立发展

1.3 CSS 语法结构

/* 选择器 */
selector {
    /* 声明块 */
    property: value;  /* 声明 */
    property: value;
}

/* 示例 */
h1 {
    color: blue;      /* 属性: 值; */
    font-size: 24px;  /* 属性: 值; */
    margin: 0;        /* 属性: 值; */
}

1.4 CSS 引入方式

  1. 行内样式

    <div style="color: red; font-size: 16px;">行内样式</div>
    
  2. 内部样式表

    <style>
        body {
            font-family: Arial, sans-serif;
        }
        h1 {
            color: #333;
        }
    </style>
    
  3. 外部样式表

    <link rel="stylesheet" href="styles.css">
    
  4. 导入样式

    @import url("reset.css");
    @import url("layout.css");
    

1.5 CSS 注释

/* 单行注释 */

/*
  多行
  注释
*/

/*! 重要注释,压缩时不会被删除 */

二、CSS 选择器

2.1 基础选择器

/* 元素选择器 */
div { color: blue; }

/* 类选择器 */
.class-name { color: red; }

/* ID选择器 */
#element-id { color: green; }

/* 通配符选择器 */
* { margin: 0; padding: 0; }

/* 属性选择器 */
[type="text"] { border: 1px solid #ccc; }
[disabled] { opacity: 0.5; }
[class^="btn-"] { /* 以btn-开头 */ }
[class$="-primary"] { /* 以-primary结尾 */ }
[class*="warning"] { /* 包含warning */ }

2.2 关系选择器

/* 后代选择器 */
div p { color: red; }           /* div内的所有p */

/* 子元素选择器 */
div > p { color: blue; }        /* div的直接子元素p */

/* 相邻兄弟选择器 */
h1 + p { margin-top: 0; }       /* 紧跟在h1后的p */

/* 通用兄弟选择器 */
h1 ~ p { color: green; }        /* h1后面的所有p */

2.3 伪类选择器

  1. 状态伪类

    /* 链接状态 */
    a:link { color: blue; }         /* 未访问 */
    a:visited { color: purple; }    /* 已访问 */
    a:hover { color: red; }         /* 鼠标悬停 */
    a:active { color: orange; }     /* 激活时 */
    a:focus { outline: 2px solid blue; } /* 获得焦点 */
    
    /* 表单状态 */
    input:enabled { background: white; }
    input:disabled { background: #eee; }
    input:checked { accent-color: red; }
    input:required { border-color: red; }
    input:optional { border-color: #ccc; }
    input:valid { border-color: green; }
    input:invalid { border-color: red; }
    input:in-range { color: green; }
    input:out-of-range { color: red; }
    
  2. 结构伪类

    /* 子元素位置 */
    li:first-child { color: red; }      /* 第一个子元素 */
    li:last-child { color: blue; }      /* 最后一个子元素 */
    li:nth-child(3) { color: green; }   /* 第3个子元素 */
    li:nth-child(odd) { background: #f0f0f0; }  /* 奇数 */
    li:nth-child(even) { background: #fff; }    /* 偶数 */
    li:nth-child(3n) { color: orange; }         /* 3的倍数 */
    li:nth-child(3n+1) { color: purple; }       /* 3n+1位置 */
    
    /* 其他结构伪类 */
    li:only-child { background: yellow; }       /* 独生子 */
    p:first-of-type { font-size: 1.2em; }       /* 同类型第一个 */
    p:last-of-type { font-size: 0.9em; }        /* 同类型最后一个 */
    p:nth-of-type(2) { color: red; }            /* 同类型第2个 */
    p:empty { display: none; }                  /* 空元素 */
    
  3. 逻辑伪类

    /* 逻辑组合 */
    :is(div, p, span) { color: blue; }     /* 匹配其中任意一个 */
    :where(div, p) { margin: 0; }          /* 同:is,但权重为0 */
    :not(.ignore) { border: 1px solid; }   /* 不匹配 */
    :not(p) { font-weight: bold; }         /* 不是p的元素 */
    
    /* 目标伪类 */
    :target { background: yellow; }        /* URL片段标识符目标 */
    

2.4 伪元素选择器

/* 内容前后插入 */
p::before { 
    content: "【前置内容】"; 
    color: red; 
}
p::after { 
    content: "【后置内容】"; 
    color: blue; 
}

/* 首字母和首行 */
p::first-letter { 
    font-size: 2em; 
    font-weight: bold; 
}
p::first-line { 
    font-weight: bold; 
    color: #333; 
}

/* 选中文本 */
::selection { 
    background: yellow; 
    color: black; 
}
::-moz-selection { 
    background: yellow; 
    color: black; 
}

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

/* 列表标记 */
li::marker { 
    color: red; 
    content: "→ "; 
}

2.5 选择器优先级

/* 优先级权重(从高到低) */
/* 1. !important */
div { color: red !important; }

/* 2. 行内样式(权重:1000) */
<div style="color: blue;">行内样式</div>

/* 3. ID选择器(权重:0100) */
#id-selector { color: green; }

/* 4. 类选择器、属性选择器、伪类(权重:0010) */
.class-selector { color: yellow; }
[type="text"] { color: purple; }
:hover { color: orange; }

/* 5. 元素选择器、伪元素(权重:0001) */
div { color: black; }
::before { content: "伪元素"; }

/* 6. 通配符、关系选择器(权重:0000) */
* { margin: 0; }
div p { color: gray; }

/* 优先级计算示例 */
#header .nav li.active a:hover { 
    /* 权重:0100 + 0010 + 0001 + 0010 + 0001 = 0122 */
    color: red; 
}

三、CSS 单位与值

3.1 绝对单位

/* 像素(最常用) */
p { font-size: 16px; }

/* 厘米 */
div { width: 10cm; }

/* 毫米 */
div { width: 100mm; }

/* 英寸 */
div { width: 4in; }  /* 1in = 96px = 2.54cm */

/* 点 */
p { font-size: 12pt; }  /* 1pt = 1/72in */

/* 派卡 */
p { font-size: 1pc; }   /* 1pc = 12pt */

3.2 相对单位

/* 相对父元素字体大小 */
.parent { font-size: 20px; }
.child { font-size: 1.5em; }  /* 30px */
.child2 { font-size: 0.5rem; } /* 8px(相对于根元素) */

/* 视口单位 */
div { 
    width: 50vw;     /* 视口宽度的50% */
    height: 100vh;   /* 视口高度的100% */
    font-size: 2vmin; /* 视口较小尺寸的2% */
    font-size: 2vmax; /* 视口较大尺寸的2% */
}

/* 字符单位 */
p { 
    width: 20ch;    /* 20个"0"字符的宽度 */
    text-indent: 2em; /* 2个字符缩进 */
}

/* 行高单位 */
p { line-height: 1.5; } /* 无单位,相对于字体大小 */

3.3 颜色值

/* 关键字颜色 */
color: red;
color: transparent;

/* 十六进制 */
color: #ff0000;      /* 红色 */
color: #f00;         /* 简写 */
color: #ff000080;    /* 带透明度 */

/* RGB/RGBA */
color: rgb(255, 0, 0);
color: rgb(100%, 0%, 0%);
color: rgba(255, 0, 0, 0.5);

/* HSL/HSLA */
color: hsl(0, 100%, 50%);      /* 色相, 饱和度, 明度 */
color: hsla(0, 100%, 50%, 0.5);

/* 现代颜色函数 */
color: lab(54% 80 -45);        /* LAB颜色空间 */
color: lch(54% 70 40);         /* LCH颜色空间 */
color: oklch(60% 0.2 250);     /* OKLCH颜色空间 */
color: color(display-p3 1 0 0); /* P3广色域 */

/* 当前颜色 */
border: 1px solid currentColor;

3.4 数值与函数

/* 基本数值 */
width: 100;
opacity: 0.5;
z-index: 10;

/* 数学函数 */
width: calc(100% - 20px);
height: calc(50vh + 10px);
font-size: min(16px, 4vw);      /* 取较小值 */
font-size: max(12px, 1vw);      /* 取较大值 */
width: clamp(200px, 50%, 600px); /* 在范围内取值 */

/* 变换函数 */
transform: rotate(45deg);
transform: scale(1.5);
transform: translate(10px, 20px);

四、盒模型

4.1 标准盒模型

.box {
    /* 内容区 */
    width: 200px;      /* 内容宽度 */
    height: 100px;     /* 内容高度 */
    
    /* 内边距 */
    padding: 20px;     /* 上下左右 */
    padding: 10px 20px;/* 上下 | 左右 */
    padding: 5px 10px 15px 20px; /* 上 右 下 左 */
    
    /* 边框 */
    border: 2px solid #333;
    border-width: 1px 2px 3px 4px;
    border-style: solid dashed dotted double;
    border-color: red green blue yellow;
    
    /* 外边距 */
    margin: 20px;
    margin: 10px auto; /* 水平居中 */
    
    /* 总宽度 = width + padding + border */
    /* 总高度 = height + padding + border */
}

4.2 怪异盒模型

.box {
    box-sizing: border-box; /* 切换到怪异盒模型 */
    width: 200px;           /* 包含padding和border */
    padding: 20px;          /* 包含在width内 */
    border: 2px solid #333; /* 包含在width内 */
    
    /* 总宽度 = width (固定) */
    /* 总高度 = height (固定) */
}

4.3 盒模型属性

/* 溢出控制 */
.box {
    overflow: visible;    /* 默认,内容可见 */
    overflow: hidden;     /* 隐藏溢出 */
    overflow: scroll;     /* 显示滚动条 */
    overflow: auto;       /* 自动显示滚动条 */
    overflow-x: hidden;   /* 水平隐藏 */
    overflow-y: scroll;   /* 垂直滚动 */
    
    /* 溢出行为 */
    overflow-wrap: break-word; /* 单词内换行 */
    word-break: break-all;     /* 任意位置换行 */
    text-overflow: ellipsis;   /* 文本溢出显示省略号 */
}

/* 显示类型 */
.box {
    display: block;        /* 块级元素 */
    display: inline;       /* 行内元素 */
    display: inline-block; /* 行内块级 */
    display: none;         /* 不显示 */
    display: flex;         /* 弹性盒子 */
    display: grid;         /* 网格布局 */
    display: contents;     /* 不生成盒子 */
}

4.4 轮廓与阴影

/* 轮廓(不占空间) */
.box {
    outline: 2px solid blue;
    outline-offset: 5px;     /* 轮廓偏移 */
    outline: none;           /* 移除焦点轮廓 */
}

/* 盒子阴影 */
.box {
    box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
    box-shadow: 0 0 10px 5px rgba(0,0,0,0.5) inset;
    box-shadow: 
        0 2px 4px rgba(0,0,0,0.1),
        0 4px 8px rgba(0,0,0,0.1);
    
    /* 参数:x偏移 y偏移 模糊半径 扩展半径 颜色 inset */
}

/* 圆角 */
.box {
    border-radius: 10px;
    border-radius: 10px 20px 30px 40px; /* 左上 右上 右下 左下 */
    border-radius: 50%;                 /* 圆形 */
    border-radius: 10px / 20px;         /* 椭圆圆角 */
}

五、布局系统

5.1 传统布局

  1. 文档流

    /* 块级元素 */
    div, p, h1 { 
        display: block; 
        width: 100%; /* 默认占满父容器 */
    }
    
    /* 行内元素 */
    span, a, em { 
        display: inline; 
        width: auto; /* 宽度由内容决定 */
    }
    
  2. 浮动布局

    .float-left {
        float: left;
        width: 200px;
        margin-right: 20px;
    }
    
    .float-right {
        float: right;
        width: 200px;
        margin-left: 20px;
    }
    
    /* 清除浮动 */
    .clearfix::after {
        content: "";
        display: table;
        clear: both;
    }
    
  3. 定位布局

    /* 相对定位 */
    .relative {
        position: relative;
        top: 10px;
        left: 20px;
        /* 相对于自身原位置偏移 */
    }
    
    /* 绝对定位 */
    .absolute {
        position: absolute;
        top: 0;
        right: 0;
        /* 相对于最近的非static定位祖先 */
    }
    
    /* 固定定位 */
    .fixed {
        position: fixed;
        bottom: 20px;
        right: 20px;
        /* 相对于视口 */
    }
    
    /* 粘性定位 */
    .sticky {
        position: sticky;
        top: 0;
        /* 相对定位和固定定位的混合 */
    }
    
    /* 堆叠上下文 */
    .z-index-1 { z-index: 1; }
    .z-index-2 { z-index: 2; }
    

5.2 Flexbox 弹性盒子

  1. 容器属性

    .flex-container {
        display: flex; /* 或 inline-flex */
            
        /* 主轴方向 */
        flex-direction: row;            /* 水平方向,起点在左端 */
        flex-direction: row-reverse;    /* 水平方向,起点在右端 */
        flex-direction: column;         /* 垂直方向,起点在上沿 */
        flex-direction: column-reverse; /* 垂直方向,起点在下沿 */
            
        /* 换行 */
        flex-wrap: nowrap;     /* 不换行 */
        flex-wrap: wrap;       /* 换行,第一行在上方 */
        flex-wrap: wrap-reverse; /* 换行,第一行在下方 */
            
        /* 简写 */
        flex-flow: row wrap;
            
        /* 主轴对齐 */
        justify-content: flex-start;    /* 起点对齐 */
        justify-content: flex-end;      /* 终点对齐 */
        justify-content: center;        /* 居中对齐 */
        justify-content: space-between; /* 两端对齐,项目间隔相等 */
        justify-content: space-around;  /* 每个项目两侧间隔相等 */
        justify-content: space-evenly;  /* 项目间隔完全相等 */
            
        /* 交叉轴对齐 */
        align-items: stretch;     /* 拉伸填满容器高度 */
        align-items: flex-start;  /* 起点对齐 */
        align-items: flex-end;    /* 终点对齐 */
        align-items: center;      /* 居中对齐 */
        align-items: baseline;    /* 基线对齐 */
            
        /* 多行对齐 */
        align-content: stretch;
        align-content: flex-start;
        align-content: flex-end;
        align-content: center;
        align-content: space-between;
        align-content: space-around;
        align-content: space-evenly;
            
        /* 间距 */
        gap: 10px;              /* 行和列间距 */
        row-gap: 10px;         /* 行间距 */
        column-gap: 20px;      /* 列间距 */
    }
    
  2. 项目属性

.flex-item {
    /* 排序 */
    order: 1; /* 数值越小,排列越靠前,默认0 */
    
    /* 放大比例 */
    flex-grow: 1; /* 默认0,不放大 */
    
    /* 缩小比例 */
    flex-shrink: 1; /* 默认1,空间不足时缩小 */
    
    /* 基础大小 */
    flex-basis: 200px; /* 项目在主轴上的初始大小 */
    flex-basis: auto;  /* 自动计算 */
    flex-basis: 0;     /* 根据内容分配空间 */
    
    /* 简写 */
    flex: 1;                  /* flex-grow: 1; flex-shrink: 1; flex-basis: 0; */
    flex: 0 0 200px;         /* flex-grow: 0; flex-shrink: 0; flex-basis: 200px; */
    flex: 2 1 auto;          /* flex-grow: 2; flex-shrink: 1; flex-basis: auto; */
    
    /* 单个项目对齐方式 */
    align-self: auto;       /* 继承父容器的align-items */
    align-self: flex-start;
    align-self: flex-end;
    align-self: center;
    align-self: baseline;
    align-self: stretch;
}

5.3 Grid 网格布局

  1. 容器属性

    .grid-container {
        display: grid; /* 或 inline-grid */
            
        /* 定义网格列 */
        grid-template-columns: 100px 200px 100px;
        grid-template-columns: 1fr 2fr 1fr; /* 分数单位 */
        grid-template-columns: repeat(3, 1fr); /* 重复 */
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        grid-template-columns: [col1] 100px [col2] 200px [col3] 100px;
            
        /* 定义网格行 */
        grid-template-rows: 100px 200px;
        grid-template-rows: min-content 1fr max-content;
            
        /* 简写 */
        grid-template: 
            "header header" 100px
            "sidebar main" 1fr
            "footer footer" 50px
            / 200px 1fr;
            
        /* 自动放置 */
        grid-auto-flow: row;           /* 默认,按行排列 */
        grid-auto-flow: column;        /* 按列排列 */
        grid-auto-flow: row dense;     /* 密集排列 */
            
        /* 隐式网格大小 */
        grid-auto-columns: 100px;
        grid-auto-rows: minmax(100px, auto);
            
        /* 间距 */
        gap: 20px;          /* 行列间距 */
        row-gap: 10px;      /* 行间距 */
        column-gap: 20px;   /* 列间距 */
            
        /* 对齐 */
        justify-items: stretch;     /* 单元格水平对齐 */
        align-items: stretch;       /* 单元格垂直对齐 */
        place-items: center;        /* 简写:align-items justify-items */
            
        /* 内容对齐 */
        justify-content: center;    /* 网格水平对齐 */
        align-content: center;      /* 网格垂直对齐 */
        place-content: center;      /* 简写 */
    }
    
  2. 项目属性

    .grid-item {
        /* 位置 */
        grid-column-start: 1;
        grid-column-end: 3;
        grid-row-start: 1;
        grid-row-end: 3;
            
        /* 简写 */
        grid-column: 1 / 3;       /* 从第1列到第3列前 */
        grid-column: 1 / span 2;  /* 从第1列开始,跨越2列 */
        grid-row: 1 / 3;          /* 从第1行到第3行前 */
            
        /* 区域 */
        grid-area: 1 / 1 / 3 / 3; /* row-start / column-start / row-end / column-end */
        grid-area: header;        /* 通过grid-template-areas定义的名称 */
            
        /* 单个项目对齐 */
        justify-self: stretch;    /* 项目在单元格内的水平对齐 */
        align-self: stretch;      /* 项目在单元格内的垂直对齐 */
        place-self: center;       /* 简写 */
    }
    
  3. 网格区域

    .grid-container {
        display: grid;
        grid-template-areas: 
            "header header header"
            "sidebar main main"
            "footer footer footer";
        grid-template-columns: 200px 1fr 1fr;
        grid-template-rows: 100px 1fr 50px;
        gap: 20px;
    }
    
    .header { grid-area: header; }
    .sidebar { grid-area: sidebar; }
    .main { grid-area: main; }
    .footer { grid-area: footer; }
    

5.4 多列布局

.multi-column {
    /* 列数 */
    column-count: 3;
    
    /* 列宽 */
    column-width: 200px;
    
    /* 简写 */
    columns: 3 200px; /* column-count column-width */
    
    /* 间距 */
    column-gap: 40px;
    
    /* 分隔线 */
    column-rule: 1px solid #ccc; /* column-rule-width style color */
    
    /* 跨列 */
    h2 {
        column-span: all; /* 或 none */
    }
    
    /* 填充方式 */
    column-fill: auto;    /* 平衡填充 */
    column-fill: balance; /* 尽可能平衡 */
}

六、背景与渐变

6.1 背景属性

.element {
    /* 背景颜色 */
    background-color: #f0f0f0;
    background-color: rgba(255, 0, 0, 0.5);
    background-color: transparent;
    
    /* 背景图片 */
    background-image: url("image.jpg");
    background-image: linear-gradient(to right, red, blue);
    background-image: url("image1.jpg"), url("image2.jpg");
    
    /* 背景重复 */
    background-repeat: repeat;     /* 默认,重复 */
    background-repeat: no-repeat;  /* 不重复 */
    background-repeat: repeat-x;   /* 水平重复 */
    background-repeat: repeat-y;   /* 垂直重复 */
    background-repeat: space;      /* 均匀分布 */
    background-repeat: round;      /* 缩放以填满 */
    
    /* 背景位置 */
    background-position: center center;
    background-position: 10px 20px;  /* x y */
    background-position: right 20px bottom 10px;
    background-position: 50% 50%;   /* 百分比 */
    
    /* 背景大小 */
    background-size: cover;        /* 覆盖整个区域,可能裁剪 */
    background-size: contain;      /* 完整显示,可能留白 */
    background-size: 100% 100%;    /* 拉伸填满 */
    background-size: 200px 150px;  /* 指定宽高 */
    background-size: auto;         /* 原始尺寸 */
    
    /* 背景固定 */
    background-attachment: scroll;  /* 随内容滚动 */
    background-attachment: fixed;   /* 固定于视口 */
    background-attachment: local;   /* 随元素内容滚动 */
    
    /* 背景裁剪 */
    background-clip: border-box;   /* 裁剪到边框盒 */
    background-clip: padding-box;  /* 裁剪到内边距盒 */
    background-clip: content-box;  /* 裁剪到内容盒 */
    background-clip: text;         /* 裁剪到文字(需-webkit-前缀) */
    
    /* 背景原点 */
    background-origin: padding-box;  /* 默认,相对于内边距盒 */
    background-origin: border-box;   /* 相对于边框盒 */
    background-origin: content-box;  /* 相对于内容盒 */
    
    /* 简写 */
    background: #f0f0f0 url("image.jpg") no-repeat center center / cover;
    
    /* 多背景 */
    background: 
        url("image1.jpg") no-repeat center center / cover,
        linear-gradient(to bottom, rgba(0,0,0,0.5), transparent);
}

6.2 线性渐变

.element {
    /* 基本语法 */
    background: linear-gradient(to right, red, blue);
    
    /* 方向 */
    background: linear-gradient(to right, red, blue);        /* 向右 */
    background: linear-gradient(to left, red, blue);         /* 向左 */
    background: linear-gradient(to bottom, red, blue);       /* 向下 */
    background: linear-gradient(to top, red, blue);          /* 向上 */
    background: linear-gradient(to bottom right, red, blue); /* 向右下 */
    background: linear-gradient(45deg, red, blue);           /* 45度角 */
    
    /* 多个颜色 */
    background: linear-gradient(to right, red, green, blue);
    background: linear-gradient(to right, red 0%, green 50%, blue 100%);
    
    /* 色标位置 */
    background: linear-gradient(to right, red 20%, blue 80%);
    background: linear-gradient(to right, red 0% 20%, blue 80% 100%);
    
    /* 硬边渐变 */
    background: linear-gradient(to right, red 0%, red 50%, blue 50%, blue 100%);
    
    /* 透明渐变 */
    background: linear-gradient(to right, rgba(255,0,0,0), rgba(255,0,0,1));
    
    /* 重复渐变 */
    background: repeating-linear-gradient(
        45deg, 
        red 0px, red 10px, 
        blue 10px, blue 20px
    );
}

6.3 径向渐变

.element {
    /* 基本语法 */
    background: radial-gradient(circle, red, blue);
    
    /* 形状 */
    background: radial-gradient(circle, red, blue);      /* 圆形 */
    background: radial-gradient(ellipse, red, blue);     /* 椭圆形 */
    
    /* 大小 */
    background: radial-gradient(closest-side, red, blue);
    background: radial-gradient(farthest-side, red, blue);
    background: radial-gradient(closest-corner, red, blue);
    background: radial-gradient(farthest-corner, red, blue);
    
    /* 位置 */
    background: radial-gradient(circle at 20% 30%, red, blue);
    background: radial-gradient(ellipse at top left, red, blue);
    
    /* 多个颜色 */
    background: radial-gradient(circle, red 0%, green 50%, blue 100%);
    
    /* 重复渐变 */
    background: repeating-radial-gradient(
        circle, 
        red 0px, red 10px, 
        blue 10px, blue 20px
    );
}

6.4 锥形渐变

.element {
    /* 基本语法 */
    background: conic-gradient(red, blue);
    
    /* 从某角度开始 */
    background: conic-gradient(from 45deg, red, blue);
    
    /* 在中心点 */
    background: conic-gradient(at 20% 30%, red, blue);
    
    /* 多个颜色 */
    background: conic-gradient(red, green, blue, red);
    background: conic-gradient(red 0deg 90deg, blue 90deg 180deg, green 180deg 270deg, yellow 270deg 360deg);
    
    /* 重复渐变 */
    background: repeating-conic-gradient(
        red 0deg 10deg, 
        blue 10deg 20deg
    );
    
    /* 创建饼图 */
    background: conic-gradient(
        red 0% 20%,
        green 20% 40%,
        blue 40% 60%,
        yellow 60% 80%,
        purple 80% 100%
    );
    border-radius: 50%;
}

6.5 背景混合模式

.element {
    /* 混合模式 */
    background-blend-mode: normal;      /* 正常 */
    background-blend-mode: multiply;    /* 正片叠底 */
    background-blend-mode: screen;      /* 滤色 */
    background-blend-mode: overlay;     /* 叠加 */
    background-blend-mode: darken;      /* 变暗 */
    background-blend-mode: lighten;     /* 变亮 */
    background-blend-mode: color-dodge; /* 颜色减淡 */
    background-blend-mode: color-burn;  /* 颜色加深 */
    background-blend-mode: hard-light;  /* 强光 */
    background-blend-mode: soft-light;  /* 柔光 */
    background-blend-mode: difference;  /* 差值 */
    background-blend-mode: exclusion;   /* 排除 */
    background-blend-mode: hue;         /* 色相 */
    background-blend-mode: saturation;  /* 饱和度 */
    background-blend-mode: color;       /* 颜色 */
    background-blend-mode: luminosity;  /* 明度 */
    
    /* 多背景混合 */
    background: 
        url("image.jpg"),
        linear-gradient(to right, red, blue);
    background-blend-mode: multiply;
    
    /* 隔离混合 */
    isolation: isolate; /* 创建新的混合上下文 */
}

七、文本与字体

7.1 字体属性

.element {
    /* 字体系列 */
    font-family: Arial, sans-serif;
    font-family: "Microsoft YaHei", "SimHei", sans-serif;
    font-family: var(--font-family);
    
    /* 字体大小 */
    font-size: 16px;
    font-size: 1rem;
    font-size: 100%;
    font-size: larger;  /* 相对大小 */
    font-size: smaller;
    
    /* 字体粗细 */
    font-weight: normal;   /* 400 */
    font-weight: bold;     /* 700 */
    font-weight: 300;      /* 数值:100-900 */
    font-weight: lighter;  /* 相对 */
    font-weight: bolder;   /* 相对 */
    
    /* 字体样式 */
    font-style: normal;
    font-style: italic;    /* 斜体 */
    font-style: oblique;   /* 倾斜 */
    
    /* 字体变形 */
    font-variant: normal;
    font-variant: small-caps; /* 小型大写字母 */
    
    /* 行高 */
    line-height: 1.5;      /* 无单位,相对于字体大小 */
    line-height: 24px;     /* 固定值 */
    line-height: normal;   /* 浏览器默认,通常1.2 */
    
    /* 简写 */
    font: italic small-caps bold 16px/1.5 Arial, sans-serif;
    font: 16px/1.5 Arial; /* 常用简写 */
}

7.2 文本属性

.element {
    /* 文本颜色 */
    color: #333;
    color: currentColor; /* 使用当前颜色 */
    
    /* 文本对齐 */
    text-align: left;     /* 左对齐 */
    text-align: right;    /* 右对齐 */
    text-align: center;   /* 居中对齐 */
    text-align: justify;  /* 两端对齐 */
    text-align: start;    /* 起始边对齐 */
    text-align: end;      /* 结束边对齐 */
    
    /* 文本装饰 */
    text-decoration: none;         /* 无装饰 */
    text-decoration: underline;    /* 下划线 */
    text-decoration: overline;     /* 上划线 */
    text-decoration: line-through; /* 删除线 */
    text-decoration: underline wavy red; /* 波浪下划线 */
    text-decoration-color: blue;   /* 装饰颜色 */
    text-decoration-style: dotted; /* 装饰样式 */
    text-decoration-thickness: 2px;/* 装饰粗细 */
    text-underline-offset: 2px;    /* 下划线偏移 */
    
    /* 文本转换 */
    text-transform: none;       /* 不转换 */
    text-transform: uppercase;  /* 全大写 */
    text-transform: lowercase;  /* 全小写 */
    text-transform: capitalize; /* 首字母大写 */
    
    /* 文本缩进 */
    text-indent: 2em;   /* 首行缩进2个字符 */
    text-indent: -2em;  /* 悬挂缩进 */
    text-indent: 20px;
    
    /* 文本阴影 */
    text-shadow: 2px 2px 2px rgba(0,0,0,0.5);
    text-shadow: 0 0 5px red, 0 0 10px blue; /* 多个阴影 */
    /* 参数:x偏移 y偏移 模糊半径 颜色 */
    
    /* 文本溢出 */
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;  /* 显示省略号 */
    text-overflow: "…";       /* 自定义省略符号 */
    
    /* 空白处理 */
    white-space: normal;      /* 合并空白,自动换行 */
    white-space: nowrap;      /* 合并空白,不换行 */
    white-space: pre;         /* 保留空白,不换行 */
    white-space: pre-wrap;    /* 保留空白,换行 */
    white-space: pre-line;    /* 合并空白,换行 */
    
    /* 换行规则 */
    word-break: normal;       /* 默认换行规则 */
    word-break: break-all;    /* 任意位置换行 */
    word-break: keep-all;     /* CJK文本不换行 */
    
    overflow-wrap: normal;    /* 默认 */
    overflow-wrap: break-word;/* 单词内换行 */
    overflow-wrap: anywhere;  /* 任意位置换行 */
    
    /* 连字符 */
    hyphens: none;     /* 不连字符 */
    hyphens: manual;   /* 手动连字符 */
    hyphens: auto;     /* 自动连字符 */
    
    /* 书写模式 */
    writing-mode: horizontal-tb;  /* 水平,从上到下 */
    writing-mode: vertical-rl;    /* 垂直,从右到左 */
    writing-mode: vertical-lr;    /* 垂直,从左到右 */
    
    /* 文本方向 */
    direction: ltr;    /* 从左到右 */
    direction: rtl;    /* 从右到左 */
    
    /* 文本渲染 */
    text-rendering: auto;         /* 自动优化 */
    text-rendering: optimizeSpeed;/* 速度优先 */
    text-rendering: optimizeLegibility; /* 可读性优先 */
    text-rendering: geometricPrecision; /* 几何精度 */
}

7.3 字体特性

.element {
    /* 字体特征设置 */
    font-feature-settings: "kern" 1;               /* 字距调整 */
    font-feature-settings: "liga" 1;               /* 连字 */
    font-feature-settings: "calt" 1;               /* 上下文替代 */
    font-feature-settings: "frac" 1;               /* 分数 */
    font-feature-settings: "smcp" 1;               /* 小型大写字母 */
    font-feature-settings: "kern", "liga", "calt"; /* 多个特性 */
    
    /* 字体变体 */
    font-variant-ligatures: normal;        /* 正常连字 */
    font-variant-ligatures: none;          /* 禁用连字 */
    font-variant-ligatures: common-ligatures; /* 常用连字 */
    
    font-variant-caps: normal;             /* 正常 */
    font-variant-caps: small-caps;         /* 小型大写 */
    font-variant-caps: all-small-caps;     /* 全部小型大写 */
    
    font-variant-numeric: normal;          /* 正常数字 */
    font-variant-numeric: lining-nums;     /* 等高数字 */
    font-variant-numeric: oldstyle-nums;   /* 旧式数字 */
    font-variant-numeric: proportional-nums; /* 比例数字 */
    font-variant-numeric: tabular-nums;    /* 等宽数字 */
    
    /* 字体变体简写 */
    font-variant: small-caps oldstyle-nums;
}

7.4 自定义字体

/* 定义字体 */
@font-face {
    font-family: 'MyFont';
    src: url('myfont.woff2') format('woff2'),
         url('myfont.woff') format('woff');
    font-weight: 400;
    font-style: normal;
    font-display: swap;         /* 字体加载策略 */
    unicode-range: U+000-5FF;   /* 字符范围 */
}

/* 使用字体 */
body {
    font-family: 'MyFont', sans-serif;
}

/* 字体显示策略 */
.element {
    font-display: auto;         /* 浏览器默认 */
    font-display: block;        /* 阻塞渲染 */
    font-display: swap;         /* 回退字体立即显示,字体加载后替换 */
    font-display: fallback;     /* 短暂阻塞,超时用回退 */
    font-display: optional;     /* 短暂阻塞,超时用回退且不替换 */
}

7.5 变量字体

@font-face {
    font-family: 'VariableFont';
    src: url('font.woff2') format('woff2-variations');
    font-weight: 100 900;      /* 可变粗细范围 */
    font-stretch: 50% 200%;    /* 可变宽度范围 */
    font-style: oblique 0deg 20deg; /* 可变倾斜 */
}

.element {
    font-family: 'VariableFont';
    font-weight: 650;          /* 中间粗细 */
    font-stretch: 120%;        /* 扩展宽度 */
    font-variation-settings: 
        "wght" 700,           /* 权重 */
        "wdth" 120,           /* 宽度 */
        "slnt" -10;           /* 倾斜 */
}

八、变换、过渡与动画

8.1 2D变换

.element {
    /* 位移 */
    transform: translate(50px, 100px);  /* x, y */
    transform: translateX(50px);        /* 水平位移 */
    transform: translateY(100px);       /* 垂直位移 */
    transform: translate(50%);          /* 百分比相对于自身 */
    
    /* 旋转 */
    transform: rotate(45deg);           /* 旋转45度 */
    transform: rotate(1turn);           /* 旋转一圈 */
    
    /* 缩放 */
    transform: scale(1.5);              /* 水平和垂直都缩放1.5倍 */
    transform: scale(1.5, 0.5);         /* x方向1.5倍,y方向0.5倍 */
    transform: scaleX(1.5);             /* 水平缩放 */
    transform: scaleY(0.5);             /* 垂直缩放 */
    
    /* 倾斜 */
    transform: skew(30deg, 20deg);      /* x方向30度,y方向20度 */
    transform: skewX(30deg);            /* 水平倾斜 */
    transform: skewY(20deg);            /* 垂直倾斜 */
    
    /* 多重变换 */
    transform: translate(50px, 100px) rotate(45deg) scale(1.5);
    
    /* 变换原点 */
    transform-origin: center center;    /* 默认,中心 */
    transform-origin: left top;         /* 左上角 */
    transform-origin: 20px 20px;        /* 具体坐标 */
    transform-origin: 0 0;              /* 左上角 */
    
    /* 变换样式 */
    transform-style: flat;              /* 子元素不保留3D位置 */
    transform-style: preserve-3d;       /* 子元素保留3D位置 */
}

8.2 3D变换

.element {
    /* 3D位移 */
    transform: translate3d(50px, 100px, 200px);
    transform: translateZ(200px);
    
    /* 3D旋转 */
    transform: rotate3d(1, 1, 1, 45deg); /* x,y,z向量旋转 */
    transform: rotateX(45deg);          /* 绕X轴旋转 */
    transform: rotateY(45deg);          /* 绕Y轴旋转 */
    transform: rotateZ(45deg);          /* 绕Z轴旋转 */
    
    /* 3D缩放 */
    transform: scale3d(1.5, 1.5, 2);
    transform: scaleZ(2);
    
    /* 透视 */
    perspective: 1000px;                /* 透视距离 */
    perspective-origin: center center;  /* 透视原点 */
    
    /* 背面可见性 */
    backface-visibility: visible;       /* 背面可见 */
    backface-visibility: hidden;        /* 背面隐藏 */
}

8.3 过渡

.element {
    /* 过渡属性 */
    transition-property: all;           /* 所有属性 */
    transition-property: opacity, transform; /* 指定属性 */
    transition-property: none;          /* 无过渡 */
    
    /* 过渡时长 */
    transition-duration: 0.3s;          /* 0.3秒 */
    transition-duration: 300ms;         /* 300毫秒 */
    transition-duration: 1s, 0.5s;      /* 多个属性不同时长 */
    
    /* 过渡函数 */
    transition-timing-function: ease;           /* 默认,慢-快-慢 */
    transition-timing-function: linear;         /* 匀速 */
    transition-timing-function: ease-in;        /* 慢-快 */
    transition-timing-function: ease-out;       /* 快-慢 */
    transition-timing-function: ease-in-out;    /* 慢-快-慢 */
    transition-timing-function: cubic-bezier(0.1, 0.7, 1.0, 0.1); /* 贝塞尔曲线 */
    transition-timing-function: steps(5, jump-start); /* 步进 */
    
    /* 过渡延迟 */
    transition-delay: 0s;               /* 无延迟 */
    transition-delay: 0.5s;             /* 0.5秒后开始 */
    transition-delay: 0s, 0.2s;         /* 多个属性不同延迟 */
    
    /* 简写 */
    transition: all 0.3s ease 0s;
    transition: opacity 0.3s, transform 0.5s ease-in-out 0.1s;
    
    /* 多个过渡 */
    transition: 
        opacity 0.3s ease,
        transform 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55);
}

8.4 动画

  1. 关键帧动画

    /* 定义动画 */
    @keyframes slideIn {
        /* 关键帧 */
        from {
            transform: translateX(-100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    /* 百分比关键帧 */
    @keyframes bounce {
        0% {
            transform: translateY(0);
        }
        50% {
            transform: translateY(-30px);
        }
        100% {
            transform: translateY(0);
        }
    }
    
    /* 使用动画 */
    .element {
        animation-name: slideIn;           /* 动画名称 */
        animation-duration: 0.5s;          /* 持续时间 */
        animation-timing-function: ease;   /* 时间函数 */
        animation-delay: 0s;               /* 延迟 */
        animation-iteration-count: 1;      /* 播放次数 */
        animation-direction: normal;       /* 播放方向 */
        animation-fill-mode: none;         /* 填充模式 */
        animation-play-state: running;     /* 播放状态 */
            
        /* 简写 */
        animation: slideIn 0.5s ease 0s 1 normal none running;
    }
    
  2. 动画属性

    .element {
        /* 播放次数 */
        animation-iteration-count: 1;      /* 播放1次 */
        animation-iteration-count: 3;      /* 播放3次 */
        animation-iteration-count: infinite; /* 无限循环 */
            
        /* 播放方向 */
        animation-direction: normal;       /* 正常播放 */
        animation-direction: reverse;      /* 反向播放 */
        animation-direction: alternate;    /* 正向交替 */
        animation-direction: alternate-reverse; /* 反向交替 */
            
        /* 填充模式 */
        animation-fill-mode: none;         /* 不应用样式 */
        animation-fill-mode: forwards;     /* 保持最后一帧 */
        animation-fill-mode: backwards;    /* 应用第一帧 */
        animation-fill-mode: both;         /* 同时应用forwards和backwards */
            
        /* 播放状态 */
        animation-play-state: running;     /* 播放中 */
        animation-play-state: paused;      /* 暂停 */
            
        /* 多个动画 */
        animation: 
            slideIn 0.5s ease,
            bounce 1s ease infinite;
    }
    
  3. 动画事件

    const element = document.querySelector('.element');
    element.addEventListener('animationstart', () => {
        console.log('动画开始');
    });
    element.addEventListener('animationend', () => {
        console.log('动画结束');
    });
    element.addEventListener('animationiteration', () => {
        console.log('动画迭代');
    });
    

8.5 变换优化

.element {
    /* 硬件加速 */
    transform: translateZ(0);
    will-change: transform;     /* 提示浏览器元素将发生变化 */
    
    /* 性能优化 */
    backface-visibility: hidden;
    perspective: 1000px;
    
    /* 避免回流 */
    transform: translateX(100px); /* 使用transform代替left/top */
}

九、响应式设计

9.1 媒体查询

/* 媒体类型 */
@media screen { }              /* 屏幕设备 */
@media print { }               /* 打印设备 */
@media speech { }              /* 语音合成器 */

/* 逻辑运算符 */
@media screen and (min-width: 768px) { }  /* 与 */
@media screen, print { }                   /* 或 */
@media not screen and (color) { }         /* 非 */

/* 常用断点 */
/* 手机 */
@media (max-width: 767px) { }

/* 平板 */
@media (min-width: 768px) and (max-width: 1023px) { }

/* 桌面 */
@media (min-width: 1024px) { }

/* 高清桌面 */
@media (min-width: 1280px) { }

/* 特性查询 */
/* 宽度 */
@media (width: 768px) { }                     /* 等于 */
@media (min-width: 768px) { }                 /* 大于等于 */
@media (max-width: 767px) { }                 /* 小于等于 */
@media (768px <= width <= 1024px) { }         /* 范围 */

/* 高度 */
@media (min-height: 600px) { }

/* 设备像素比 */
@media (-webkit-min-device-pixel-ratio: 2), 
       (min-resolution: 192dpi) { }

/* 方向 */
@media (orientation: portrait) { }           /* 竖屏 */
@media (orientation: landscape) { }          /* 横屏 */

/* 宽高比 */
@media (aspect-ratio: 16/9) { }

/* 颜色 */
@media (color) { }                           /* 彩色设备 */
@media (min-color: 8) { }                    /* 至少8位颜色 */

/* 交互能力 */
@media (hover: hover) { }                    /* 支持悬停 */
@media (pointer: fine) { }                   /* 精确指针(鼠标) */
@media (pointer: coarse) { }                 /* 粗糙指针(触摸) */
@media (pointer: none) { }                   /* 无指针(键盘) */

/* 脚本支持 */
@media (scripting: enabled) { }              /* 脚本可用 */
@media (scripting: none) { }                 /* 脚本不可用 */

/* 动态查询 */
.container {
    container-type: inline-size;
}
@container (min-width: 700px) {
    .card { display: flex; }
}

9.2 响应式单位

.element {
    /* 视口单位 */
    width: 100vw;               /* 视口宽度 */
    height: 100vh;              /* 视口高度 */
    font-size: 5vmin;           /* 视口较小尺寸的5% */
    font-size: 5vmax;           /* 视口较大尺寸的5% */
    
    /* 容器查询单位 */
    width: 100cqw;              /* 容器宽度 */
    height: 100cqh;             /* 容器高度 */
    
    /* 响应式字体大小 */
    font-size: clamp(1rem, 2.5vw, 2rem);
    font-size: calc(1rem + 1vw);
    
    /* 响应式间距 */
    padding: max(1rem, 5vw);
    margin: min(2rem, 10vw);
}

9.3 响应式图片

/* 图片容器 */
.image-container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}

/* 响应式图片 */
.responsive-img {
    width: 100%;
    height: auto;
    display: block;
}

/* 背景图片响应式 */
.hero {
    background-image: url('image-small.jpg');
    background-size: cover;
    background-position: center;
    
    @media (min-width: 768px) {
        background-image: url('image-medium.jpg');
    }
    
    @media (min-width: 1200px) {
        background-image: url('image-large.jpg');
    }
}

/* 响应式图标 */
.icon {
    width: 1em;
    height: 1em;
    font-size: 2rem;
    
    @media (min-width: 768px) {
        font-size: 2.5rem;
    }
}

9.4 移动优先设计

/* 移动优先 - 从小屏幕开始 */
.element {
    /* 移动端样式 */
    padding: 1rem;
    font-size: 1rem;
    
    /* 平板 */
    @media (min-width: 768px) {
        padding: 1.5rem;
        font-size: 1.1rem;
    }
    
    /* 桌面 */
    @media (min-width: 1024px) {
        padding: 2rem;
        font-size: 1.2rem;
    }
}

/* 桌面优先 - 从大屏幕开始 */
.element {
    /* 桌面样式 */
    padding: 2rem;
    font-size: 1.2rem;
    
    /* 平板 */
    @media (max-width: 1023px) {
        padding: 1.5rem;
        font-size: 1.1rem;
    }
    
    /* 手机 */
    @media (max-width: 767px) {
        padding: 1rem;
        font-size: 1rem;
    }
}

十、CSS 架构与工程化

10.1 CSS 方法论

  1. BEM (Block Element Modifier)

    /* 块 */
    .button { }
    
    /* 元素 */
    .button__icon { }
    .button__text { }
    
    /* 修饰符 */
    .button--primary { }
    .button--large { }
    .button--disabled { }
    .button--active { }
    
  2. OOCSS (Object Oriented CSS)

    /* 结构 */
    .media { display: flex; }
    .media__image { margin-right: 1rem; }
    .media__content { flex: 1; }
    
    /* 皮肤 */
    .primary { color: blue; }
    .large { font-size: 1.5rem; }
    .rounded { border-radius: 0.5rem; }
    
  3. SMACSS (Scalable Modular Architecture)

    /* 基础规则 */
    html, body { margin: 0; }
    a { color: blue; }
    
    /* 布局规则 */
    .l-header { }
    .l-footer { }
    .l-grid { }
    
    /* 模块规则 */
    .btn { }
    .card { }
    .modal { }
    
    /* 状态规则 */
    .is-hidden { display: none; }
    .is-active { background: blue; }
    .has-error { border-color: red; }
    
    /* 主题规则 */
    .theme-dark { background: #333; }
    .theme-light { background: #fff; }
    
  4. ITCSS (Inverted Triangle CSS)

    /* 设置层 - 变量、配置 */
    :root { --primary-color: blue; }
    
    /* 工具层 - mixins、函数 */
    .u-text-center { text-align: center; }
    
    /* 通用层 - 重置、规范化 */
    * { box-sizing: border-box; }
    
    /* 元素层 - 原生元素样式 */
    h1 { font-size: 2rem; }
    
    /* 对象层 - 无皮肤的结构对象 */
    .o-container { max-width: 1200px; }
    
    /* 组件层 - 具体UI组件 */
    .c-button { padding: 0.5rem 1rem; }
    
    /* 工具层 - 辅助类 */
    .truncate { white-space: nowrap; }
    

10.2 CSS 自定义属性

:root {
    /* 定义变量 */
    --primary-color: #007bff;
    --secondary-color: #6c757d;
    --font-size-base: 16px;
    --spacing-unit: 8px;
    --max-width: 1200px;
    
    /* 计算变量 */
    --spacing-sm: calc(var(--spacing-unit) * 0.5);
    --spacing-md: calc(var(--spacing-unit) * 1);
    --spacing-lg: calc(var(--spacing-unit) * 2);
    
    /* 颜色系统 */
    --color-primary: oklch(60% 0.2 250);
    --color-surface: oklch(98% 0.02 250);
    --color-text: oklch(20% 0.02 250);
}

/* 使用变量 */
.element {
    color: var(--primary-color);
    font-size: var(--font-size-base);
    margin: var(--spacing-md);
    max-width: var(--max-width);
}

/* 变量回退 */
.element {
    color: var(--custom-color, blue);
}

/* 动态变量 */
.element {
    --local-size: 20px;
    font-size: var(--local-size);
}

/* 在JavaScript中使用 */
document.documentElement.style.setProperty('--primary-color', 'red');

10.3 CSS 作用域

/* 全局作用域 */
:root { --global-color: red; }

/* 元素作用域 */
.element { --local-color: blue; }

/* 组件作用域 - CSS Modules */
:local(.className) { color: red; }
:global(.globalClass) { color: blue; }

/* Shadow DOM 作用域 */
/* 在JavaScript中创建Shadow DOM,CSS自动作用域化 */

10.4 CSS 性能优化

/* 选择器性能 */
/* 好 - 具体选择器 */
.button-primary { }

/* 不好 - 通用选择器 */
* { }

/* 不好 - 后代选择器过多 */
div section article p span { }

/* 层叠性能 */
/* 避免过多的层叠 */
.element { 
    color: red; 
    /* 不是: .element { color: red; } .element { font-size: 16px; } */
}

/* 渲染性能 */
/* 使用transform和opacity进行动画(GPU加速) */
.element { 
    transform: translateX(100px); 
    opacity: 0.5;
}

/* 避免布局抖动 */
/* 批量读取和写入DOM */

十一、现代 CSS 特性

11.1 容器查询

/* 定义容器 */
.container {
    container-type: inline-size;
    container-name: main;
}

/* 容器查询 */
@container main (min-width: 700px) {
    .card {
        display: flex;
    }
}

@container (width > 400px) {
    .card {
        padding: 2rem;
    }
}

/* 容器查询单位 */
.card {
    width: 100cqw;  /* 容器宽度的100% */
    height: 50cqh;  /* 容器高度的50% */
    font-size: 5cqi; /* 容器内联尺寸的5% */
}

11.2 层叠层

/* 定义层 */
@layer base, components, utilities;

/* 按顺序定义层 */
@layer base {
    h1 { font-size: 2rem; }
}

@layer components {
    .button { padding: 0.5rem 1rem; }
}

@layer utilities {
    .text-center { text-align: center; }
}

/* 匿名层 */
@layer {
    .anonymous { color: red; }
}

/* 嵌套层 */
@layer framework {
    @layer default {
        p { margin: 0; }
    }
}

/* 导入到层 */
@import url("components.css") layer(components);

11.3 作用域样式

/* @scope 规则 */
@scope (.card) to (.content) {
    p { color: blue; }  /* 只影响.card内的p,但不包括.content内的p */
}

/* 作用域根和边界 */
@scope (.media) to (.media__content) {
    img { border-radius: 50%; }
}

11.4 嵌套规则

/* CSS 嵌套语法 */
.card {
    /* 直接嵌套 */
    .title {
        font-size: 1.5rem;
        
        &:hover {
            color: blue;
        }
    }
    
    /* 使用 & 引用父元素 */
    &--large {
        padding: 2rem;
    }
    
    /* 媒体查询嵌套 */
    @media (min-width: 768px) {
        display: flex;
    }
}

/* 嵌套中的 @规则 */
.component {
    @scope (&) {
        p { color: red; }
    }
}

11.5 新的伪类

/* :has() 父选择器 */
.card:has(img) { border: 2px solid blue; }
.container:has(.active) { background: yellow; }

/* 表单验证伪类 */
input:user-valid { border-color: green; }
input:user-invalid { border-color: red; }

/* 模态伪类 */
:modal { 
    /* 对话框样式 */
    background: white;
    padding: 2rem;
}

/* 全屏伪类 */
:fullscreen { background: black; }

十二、浏览器兼容性

12.1 前缀处理

.element {
    /* 标准属性 */
    display: flex;
    
    /* 带前缀版本 */
    display: -webkit-flex;
    display: -moz-flex;
    display: -ms-flexbox;
}

/* 使用PostCSS Autoprefixer自动添加 */

12.2 特性检测

/* @supports 规则 */
@supports (display: grid) {
    .container {
        display: grid;
    }
}

@supports not (display: grid) {
    .container {
        display: flex;
    }
}

@supports (display: grid) and (gap: 1rem) {
    .container {
        gap: 1rem;
    }
}

12.3 渐进增强

/* 基础样式 - 所有浏览器 */
.button {
    padding: 0.5rem 1rem;
    border: 1px solid #ccc;
    background: #f0f0f0;
}

/* 增强样式 - 支持特定特性的浏览器 */
@supports (display: flex) {
    .button {
        display: inline-flex;
        align-items: center;
    }
}

12.4 优雅降级

/* 现代样式 */
.button {
    display: grid;
    place-items: center;
    padding: 1rem;
    
    /* 回退方案 */
    display: flex;
    justify-content: center;
    align-items: center;
}

十三、CSS 工具与工作流

13.1 预处理语言

  1. Sass/SCSS

    // 变量
    $primary-color: #007bff;
    $font-stack: Helvetica, sans-serif;
    
    // 嵌套
    nav {
    ul {
        margin: 0;
        padding: 0;
        list-style: none;
    }
        
    li { display: inline-block; }
        
    a {
        color: $primary-color;
            
        &:hover {
        text-decoration: underline;
        }
    }
    }
    
    // 混合
    @mixin border-radius($radius) {
    -webkit-border-radius: $radius;
        -moz-border-radius: $radius;
        -ms-border-radius: $radius;
            border-radius: $radius;
    }
    
    .box { @include border-radius(10px); }
    
    // 继承
    %message-shared {
    border: 1px solid #ccc;
    padding: 10px;
    }
    
    .success { @extend %message-shared; border-color: green; }
    
  2. Less

    // 变量
    @primary-color: #007bff;
    @font-stack: Helvetica, sans-serif;
    
    // 混合
    .border-radius(@radius: 5px) {
    -webkit-border-radius: @radius;
        -moz-border-radius: @radius;
            border-radius: @radius;
    }
    
    .box { .border-radius(10px); }
    

13.2 后处理工具

  1. PostCSS

    // postcss.config.js
    module.exports = {
    plugins: [
        require('autoprefixer'),
        require('cssnano'),
        require('postcss-preset-env')
    ]
    }
    
  2. CSS-in-JS

    // styled-components
    import styled from 'styled-components';
    
    const Button = styled.button`
    background: ${props => props.primary ? 'blue' : 'white'};
    color: ${props => props.primary ? 'white' : 'blue'};
    font-size: 1em;
    padding: 0.5em 1em;
    `;
    

13.3 构建工具

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader'
        ]
      },
      {
        test: /\.scss$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader',
          'sass-loader'
        ]
      }
    ]
  }
};

13.4 实用工具

  1. Tailwind CSS

    <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
    按钮
    </button>
    
  2. CSS 框架

    • Bootstrap
    • Bulma
    • Foundation
    • Materialize

十四、CSS 最佳实践

14.1 代码组织

/* 1. 重置和全局样式 */
* { box-sizing: border-box; }
html { font-size: 16px; }

/* 2. 变量定义 */
:root { 
    --primary-color: #007bff;
    --spacing-unit: 8px;
}

/* 3. 工具类 */
.text-center { text-align: center; }
.mt-1 { margin-top: var(--spacing-unit); }

/* 4. 基础元素样式 */
h1, h2, h3 { margin: 0; }
a { color: var(--primary-color); }

/* 5. 布局样式 */
.container { max-width: 1200px; }
.grid { display: grid; }

/* 6. 组件样式 */
.button { padding: 0.5rem 1rem; }
.card { border: 1px solid #ccc; }

/* 7. 页面特定样式 */
.home-hero { background: #f0f0f0; }

/* 8. 辅助类 */
.hidden { display: none; }

14.2 命名约定

  1. 语义化命名

    /* 不好 */
    .red-button { }
    .big-text { }
    
    /* 好 */
    .button-primary { }
    .heading-large { }
    
  2. 命名空间

    /* 组件 */
    .c-button { }
    .c-card { }
    
    /* 布局 */
    .l-header { }
    .l-grid { }
    
    /* 工具 */
    .u-text-center { }
    .u-mt-1 { }
    
    /* 状态 */
    .is-active { }
    .has-error { }
    

14.3 性能最佳实践

/* 1. 减少选择器复杂度 */
/* 不好 */
div.content > ul.list > li.item > a.link { }

/* 好 */
.nav-link { }

/* 2. 避免通配符滥用 */
/* 不好 */
* { margin: 0; }

/* 3. 压缩CSS */
/* 使用工具:cssnano, clean-css */

/* 4. 关键CSS内联 */
<style>
  /* 首屏关键样式 */
</style>

/* 5. 延迟加载非关键CSS */
<link rel="preload" href="styles.css" as="style" onload="this.rel='stylesheet'">

14.4 可维护性

/* 1. 使用注释 */
/* ========================
   按钮组件
   ======================== */
.button { }

/* 2. 模块化CSS */
/* button.css */
.button { }

/* 3. 一致的格式 */
/* 使用Prettier或Stylelint */

/* 4. 版本控制 */
/* 将CSS文件纳入版本控制 */

十五、CSS 调试与测试

15.1 调试工具

  1. 浏览器开发者工具

    /* Chrome DevTools */
    /* 1. 检查元素 */
    /* 2. 修改样式实时预览 */
    /* 3. 盒模型查看 */
    /* 4. 颜色选择器 */
    /* 5. 动画检查器 */
    
    /* Firefox DevTools */
    /* 1. 网格检查器 */
    /* 2. 弹性盒子检查器 */
    
  2. CSS 验证器

    • W3C CSS Validator
    • Stylelint

15.2 测试策略

/* 1. 视觉回归测试 */
/* 使用工具:BackstopJS, Percy */

/* 2. 跨浏览器测试 */
/* 使用工具:BrowserStack, LambdaTest */

/* 3. 性能测试 */
/* 使用工具:Lighthouse, WebPageTest */

15.3 调试技巧

/* 1. 边框调试法 */
.debug {
    border: 1px solid red !important;
}

/* 2. 背景色调试 */
.debug-bg {
    background: rgba(255,0,0,0.1) !important;
}

/* 3. 轮廓调试 */
.debug-outline {
    outline: 2px solid blue !important;
}

/* 4. 控制台调试 */
console.log(getComputedStyle(element).property);


十六、学习资源

16.1 官方文档

  • MDN Web Docs:最全面的 CSS 文档,包含每个属性的详细说明、示例和浏览器兼容性
  • W3C CSS 规范:CSS 标准官方文档,了解最新特性和规范
  • CSS Working Group 草案:CSS 新特性的最新进展
  • Can I Use:查询 CSS 属性在各浏览器的兼容性
  • Chrome Platform Status:Chrome 浏览器对 CSS 特性的支持状态

16.2 在线教程

  • freeCodeCamp:免费的交互式 CSS 课程
  • Codecademy:付费的交互式 CSS 课程
  • CSS-Tricks:CSS 教程、技巧和文章
  • Smashing Magazine:高质量的 CSS 教程和最佳实践
  • web.dev:Google 的现代 Web 开发教程
  • Frontend Masters:付费的深度前端课程
  • Udemy/Coursera:付费的 CSS 课程

16.3 书籍推荐

  1. 入门书籍
    • 《CSS 权威指南》 - Eric A. Meyer
    • 《CSS 揭秘》 - Lea Verou
    • 《精通 CSS》 - Andy Budd
  2. 进阶书籍
    • 《CSS 新世界》 - 张鑫旭
    • 《深入解析 CSS》 - Keith J. Grant
    • 《CSS 大师》 - Tiffany B. Brown
  3. 参考书籍
    • 《CSS 规范》 - W3C
    • 《响应式 Web 设计》 - Ethan Marcotte

16.4 社区与论坛

  • Stack Overflow:CSS 问题解答社区
  • GitHub:开源 CSS 项目和框架
  • Dev.to:开发者社区,CSS 相关文章
  • CSS-Tricks 论坛:CSS 讨论社区
  • Reddit 的 r/css:CSS 相关讨论
  • 掘金/思否:中文技术社区
  • Twitter 的 #css:CSS 最新动态

16.5 工具与资源

  1. 开发工具
    • VS Code:代码编辑器,CSS 扩展丰富
    • Chrome DevTools:浏览器开发者工具
    • Firefox Developer Edition:Firefox 开发者工具
    • Safari Web Inspector:Safari 开发者工具
  2. 构建工具
    • PostCSS:CSS 后处理器
    • Autoprefixer:自动添加浏览器前缀
    • Stylelint:CSS 代码检查
    • Prettier:代码格式化
    • PurgeCSS:删除未使用的 CSS
  3. 在线工具
    • CodePen:在线代码编辑和展示
    • JSFiddle:在线代码测试
    • CSS Gradient Generator:渐变生成器
    • CSS Grid Generator:网格布局生成器
    • Flexbox Froggy:Flexbox 学习游戏
    • Grid Garden:Grid 布局学习游戏
    • CSS Specificity Calculator:选择器权重计算器
    • BrowserStack:跨浏览器测试
    • LambdaTest:在线浏览器测试
  4. 性能工具
    • Lighthouse:网站质量审计
    • WebPageTest:网站性能测试
    • PageSpeed Insights:页面速度分析
    • CSS Stats:CSS 代码统计和分析
  5. 设计工具
    • Figma:设计工具,CSS 代码生成
    • Adobe XD:设计工具
    • Sketch:设计工具
    • Zeplin:设计稿标注工具

16.6 进阶方向

  1. CSS 架构
    • BEM、OOCSS、SMACSS、ITCSS
    • 设计令牌、CSS 自定义属性系统
    • 原子化 CSS、实用类优先
  2. CSS-in-JS
    • styled-components
    • Emotion
    • Stitches
    • Vanilla Extract
  3. CSS 预处理器
    • Sass/SCSS
    • Less
    • Stylus
  4. CSS 框架
    • Tailwind CSS
    • Bootstrap
    • Bulma
    • Foundation
    • Material-UI
  5. 动画与交互
    • CSS 动画性能优化
    • Web 动画 API
    • 交互动画设计
    • Lottie 动画
  6. 响应式设计
    • 容器查询
    • 响应式图片
    • 自适应排版
    • 移动优先设计
  7. 可访问性
    • WCAG 标准
    • 屏幕阅读器兼容
    • 键盘导航
    • 高对比度模式
  8. 性能优化
    • 关键 CSS
    • 代码分割
    • 树摇
    • 字体优化
    • 图片优化
  9. 新兴特性
    • CSS 嵌套
    • 层叠层
    • 作用域样式
    • 容器查询
    • 子网格
    • 三角函数
    • 相对颜色语法
  10. 工程化
    • CSS Modules
    • CSS 打包优化
    • 样式隔离
    • 主题系统
    • 设计系统

16.7 实践项目

  1. 个人作品集网站
  2. 电商网站 UI
  3. 管理系统界面
  4. 移动端 Web 应用
  5. 数据可视化仪表盘
  6. CSS 艺术创作
  7. CSS 游戏开发
  8. CSS 动画库
  9. CSS 框架开发
  10. 设计系统建设

16.8 认证与培训

  1. W3C 认证:Web 开发认证
  2. Google 认证:移动 Web 专家
  3. 微软认证:前端开发认证
  4. 培训机构:线下/线上培训课程
  5. 大学课程:计算机相关专业课程

16.9 持续学习

  1. 关注博客
    • CSS-Tricks
    • Smashing Magazine
    • web.dev
    • Chrome Developers Blog
    • Mozilla Hacks
  2. 参加会议
    • CSS Conf
    • Frontend Love
    • Chrome Dev Summit
    • JSConf
  3. 播客
    • Syntax FM
    • ShopTalk Show
    • The CSS Podcast
  4. 社交媒体
    • Twitter 关注 CSS 专家
    • LinkedIn 加入前端群组
    • GitHub 关注 CSS 项目
  5. 贡献开源
    • 参与 CSS 框架开发
    • 提交 CSS 规范建议
    • 编写 CSS 工具
    • 翻译 CSS 文档

16.10 职业发展

  1. 前端工程师
  2. UI 工程师
  3. CSS 架构师
  4. 设计系统工程师
  5. Web 性能工程师
  6. 可访问性专家
  7. 技术作家
  8. 讲师/培训师

16.11 学习建议

  1. 基础优先:先掌握 CSS 基础,再学习高级特性
  2. 实践为主:多写代码,多做项目
  3. 理解原理:理解 CSS 渲染原理,而不只是记属性
  4. 关注标准:了解 CSS 标准发展
  5. 社区参与:参与社区讨论,学习他人经验
  6. 持续更新:CSS 发展快速,需要持续学习
  7. 建立作品集:展示个人 CSS 技能
  8. 分享知识:通过博客、演讲分享学习心得
  9. 跨学科学习:学习设计、用户体验等相关知识
  10. 保持好奇心:探索 CSS 的新可能性和创意应用
    • 建立作品集:展示个人能力

Tags:

Categories:

Updated: