目录 CONTENTS
CSS 简介
CSS 即层叠样式表(Cascading Style Sheets),用于描述 HTML 文档的样式和布局,实现网页内容与表现的分离。CSS 由 W3C(万维网联盟) 制定和维护,当前以模块化方式演进(CSS3 泛指 CSS Level 3 及之后的模块)。CSS 不能独立存在,必须依附于 HTML 文件,通过选择器与 HTML 元素建立关联。
引入 CSS 的三种方式:内联样式(style 属性)、内部样式表(<style> 标签)、外部样式表(<link> 引用 .css 文件)。
<!-- 内联样式 -->
<p style="color: red; font-size: 16px;">红色文本</p>
<!-- 内部样式表 -->
<head>
<style>
p { color: red; font-size: 16px; }
</style>
</head>
<!-- 外部样式表 -->
<head>
<link rel="stylesheet" href="styles.css">
</head>
三种方式的取舍:外部样式表最佳(样式与结构分离、可被浏览器缓存、一个 CSS 文件可被多个页面复用、便于维护和团队协作);内部样式表适用于单页或页面特有样式;内联样式优先级最高但不推荐,难以维护和复用;@import 导入性能较差,不推荐。
语法与层叠
语法结构
CSS 规则由选择器(selector)和声明块(declaration block)组成,声明块包含一个或多个属性-值对(property: value)。
选择器 {
属性1: 值1;
属性2: 值2;
}
/* 示例 */
h1 {
color: #333;
font-size: 24px;
margin-bottom: 16px;
}
注释使用 /* 注释内容 */ 包裹,支持多行。
层叠(Cascade)
当多个规则作用于同一元素时,浏览器按照优先级和顺序决定最终样式,这就是"层叠"的含义。样式来源优先级从低到高:
- 浏览器默认样式(user agent stylesheet)
- 用户自定义样式
- 外部样式表 / 内部样式表(按引入顺序,后引入的覆盖先引入的)
- 内联样式(style 属性)
!important` 声明(慎用,会打破层叠规则)
/* 外部样式表 */
p { color: blue; }
/* 内部样式表(后引入,覆盖外部) */
p { color: green; }
/* 内联样式(优先级最高) */
/* <p style="color: red;">这段文本是红色</p> */
继承(Inheritance)
某些 CSS 属性会自动从父元素传递给子元素,无需为每个子元素重复设置。
- 可继承的属性(文本相关):
color、font-family、font-size、line-height、text-align、letter-spacing等 - 不可继承的属性(盒模型相关):
width、height、margin、padding、border、background等 - 使用
inherit关键字可以强制继承父元素的值
body {
color: #333;
font-family: "Microsoft YaHei", sans-serif;
}
.child {
border: inherit; /* 强制继承父元素的 border */
}
优先级(Specificity)
| 优先级 | 选择器类型 | 示例 |
|---|---|---|
| 最高 | 内联样式 | style="color: red;" |
| 高 | ID 选择器 | #header { } |
| 中 | 类选择器、属性选择器、伪类 | .nav { }、[type="text"] { }、:hover { } |
| 低 | 元素选择器、伪元素 | p { }、::before { } |
| 最低 | 通用选择器 | * { } |
优先级可以按四元组计算:
p /* 优先级: 0,0,0,1 */
.text /* 优先级: 0,0,1,0 */
#main .text /* 优先级: 0,1,0,1 */
.container p.text /* 优先级: 0,0,2,1 */
#sidebar .item.active /* 优先级: 0,1,2,0 */
优先级相同时,后定义的规则覆盖先定义的规则;!important 可强制提升优先级,但应避免滥用——它会打破层叠规则、使优先级混乱、难以调试维护,后续覆盖需要更多 !important,形成恶性循环。正确做法是通过提高选择器优先级或调整代码顺序来解决。
选择器
基础选择器
- 通用选择器
*: 匹配页面所有元素,常用于重置样式 - 元素选择器: 使用元素名称匹配所有该类型元素
- 类选择器
.classname: 最常用,一个元素可有多个 class(空格分隔),同一个 class 可被多个元素使用 - ID 选择器
#idname: id 在页面中应唯一,优先级高于类选择器,但不推荐过度使用
* { margin: 0; padding: 0; box-sizing: border-box; }
p { color: #333; line-height: 1.6; }
.btn { padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; }
.btn-primary { background-color: #007bff; color: white; }
#main-header { background-color: #333; color: white; padding: 20px; }
组合选择器
- 后代选择器(空格): 匹配指定元素的所有后代(子、孙等)
- 子选择器
>: 仅匹配直接子元素 - 相邻兄弟选择器
+: 匹配紧接在指定元素之后的同级元素 - 通用兄弟选择器
~: 匹配指定元素之后的所有同级元素
.main-nav a { color: #007bff; text-decoration: none; }
.menu > li { padding: 10px; border-bottom: 1px solid #ddd; }
h2 + p { font-size: 1.2em; color: #666; }
h2 ~ p { margin-left: 20px; }
属性选择器
根据元素的属性及其值选择元素:
[type="text"] { border: 1px solid #ccc; }
[type^="pass"] { border-color: #ff9800; } /* 以 "pass" 开头 */
[href$=".pdf"]::after { content: " (PDF)"; } /* 以 ".pdf" 结尾 */
[href*="https"] { color: #d63384; } /* 包含 "https" */
伪类与伪元素
状态伪类:
a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; text-decoration: underline; }
a:active { color: orange; }
input:focus { border-color: #007bff; box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25); }
button:disabled { opacity: 0.5; cursor: not-allowed; }
input:checked + label { font-weight: bold; }
结构伪类:
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(2) { color: red; }
li:nth-child(even) { background-color: #f8f9fa; }
li:nth-child(odd) { background-color: #fff; }
li:nth-child(n+3) { font-size: 0.9em; }
.list li:not(.active) { opacity: 0.7; }
伪元素使用 :: 语法(CSS3 规范):
.article::first-letter { font-size: 3em; float: left; margin-right: 8px; color: #007bff; }
.article::first-line { font-weight: bold; }
.box::before { content: "★ "; color: gold; }
.box::after { content: " ✓"; color: green; }
input::placeholder { color: #aaa; font-style: italic; }
::selection { background-color: #007bff; color: white; }
盒模型
在 CSS 中,每个 HTML 元素都可以看作一个矩形盒子,从内到外依次是 content(内容)→ padding(内边距)→ border(边框)→ margin(外边距)。
┌─────────────────────────────────┐
│ margin (外边距) │
│ ┌─────────────────────────────┐ │
│ │ border (边框) │ │
│ │ ┌─────────────────────────┐│ │
│ │ │ padding (内边距) ││ │
│ │ │ ┌─────────────────────┐││ │
│ │ │ │ content (内容) │││ │
四个部分的写法
.box { width: 300px; height: 200px; background-color: #f0f0f0; }
/* padding 简写: 上 右 下 左(顺时针) */
.box { padding: 10px 20px 10px 20px; }
.box { padding: 10px 20px; } /* 上下 左右 */
.box { padding: 15px; } /* 四方向相同 */
.box { border: 2px solid #333; }
.box { border-radius: 8px; }
/* margin 简写同 padding */
.box { width: 800px; margin: 0 auto; } /* 块级元素水平居中 */
.overlap { margin-top: -20px; } /* 外边距可为负值 */
box-sizing
box-sizing 决定 width/height 的计算方式:
content-box(默认): width/height 仅包含内容区域border-box(推荐): width/height 包含内容、padding 和 border
.box {
box-sizing: content-box;
width: 300px;
padding: 20px;
border: 2px solid #333;
/* 实际占用宽度: 300 + 20*2 + 2*2 = 344px */
}
.box {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 2px solid #333;
/* 实际占用宽度: 300px(内容区域自动缩小为 256px) */
}
实际开发推荐全局设置:
*, *::before, *::after {
box-sizing: border-box;
}
顺带一提,border-box 的行为就是早期 IE 盒模型的行为;现代浏览器默认使用标准盒模型,但通过 box-sizing: border-box 可以切换。
外边距合并
两个垂直相邻元素都设置外边距时,它们之间的外边距不叠加,而是取较大值:
.box1 { margin-bottom: 30px; }
.box2 { margin-top: 20px; }
/* 两个盒子之间的实际距离: 30px(不是 50px) */
父元素与第一个子元素之间也会发生合并——若父元素没有 border 或 padding,子元素的 margin-top 会"穿透"父元素。防止方法:
.parent { border-top: 1px solid transparent; } /* 方法1: 加 border */
.parent { padding-top: 1px; } /* 方法2: 加 padding */
.parent { overflow: hidden; } /* 方法3: 触发 BFC */
应用示例
.btn {
box-sizing: border-box;
display: inline-block;
padding: 10px 24px;
border: 2px solid #007bff;
border-radius: 6px;
background-color: #007bff;
color: white;
font-size: 16px;
cursor: pointer;
}
.btn:hover { background-color: #0056b3; border-color: #0056b3; }
.card {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
margin: 16px;
background-color: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
布局
display 属性
| 值 | 说明 |
|---|---|
block |
块级元素:独占一行,可设置宽高 |
inline |
行内元素:不独占一行,不可设置宽高 |
inline-block |
行内块元素:不独占一行,可设置宽高 |
flex |
Flex 容器 |
grid |
Grid 容器 |
none |
隐藏元素(不占据空间) |
.inline { display: inline; }
.inline-block { display: inline-block; width: 200px; vertical-align: top; }
Flex 布局(最常用)
Flex 是一维布局模型,适合单行或单列场景。容器属性:
.container {
display: flex;
flex-direction: row; /* row | row-reverse | column | column-reverse */
justify-content: space-between; /* 主轴对齐 */
align-items: center; /* 交叉轴对齐 */
flex-wrap: wrap; /* 是否换行 */
gap: 16px; /* 项目间距 */
}
项目属性:
.item {
flex-grow: 1; /* 放大比例 */
flex-shrink: 1; /* 缩小比例 */
flex-basis: 200px; /* 分配多余空间前的初始大小 */
flex: 1; /* 简写,等价于 flex: 1 1 0% */
align-self: center;
order: -1; /* 排列顺序 */
}
导航栏示例:
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
background-color: #333;
}
.nav-links { display: flex; gap: 24px; list-style: none; }
.nav-links a { color: white; text-decoration: none; }
Grid 布局(常用)
Grid 是二维布局模型,可同时处理行和列:
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* 自动填充 */
gap: 16px;
place-items: center; /* 水平垂直都居中 */
}
.item {
grid-column: 1 / 3; /* 从第 1 条线到第 3 条线 */
grid-column: span 2; /* 占 2 列 */
grid-area: 1 / 1 / 3 / 3; /* 起始行 / 起始列 / 结束行 / 结束列 */
}
命名区域布局:
.page {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: 60px 1fr 80px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
.header { grid-area: header; background: #333; color: white; }
.sidebar { grid-area: sidebar; background: #f5f5f5; }
.main { grid-area: main; padding: 20px; }
.footer { grid-area: footer; background: #333; color: white; }
Flex 与 Grid 的取舍:
| 特性 | Flex 布局 | Grid 布局 |
|---|---|---|
| 维度 | 一维(行或列) | 二维(行和列) |
| 适用场景 | 导航栏、列表、居中 | 页面整体布局、复杂网格 |
| 对齐方式 | 主轴 + 交叉轴 | 行 + 列 |
| 常用度 | 最常用 | 常用 |
一维排列用 Flex,二维布局用 Grid。
定位
| 值 | 说明 |
|---|---|
static |
默认值,正常文档流 |
relative |
相对定位,相对自身原始位置,不脱离文档流 |
absolute |
绝对定位,相对最近的已定位祖先元素 |
fixed |
固定定位,相对视口,滚动时位置不变 |
sticky |
粘性定位,在 relative 和 fixed 之间切换 |
.parent { position: relative; } /* 作为定位参考 */
.child { position: absolute; top: 10px; right: 10px; }
.fixed-btn { position: fixed; bottom: 20px; right: 20px; z-index: 1000; }
.sticky-header { position: sticky; top: 0; z-index: 100; }
z-index 指定堆叠顺序,仅在定位元素上生效。
浮动与多列
浮动最初用于文字环绕图片,后来被用于布局,现在已被 Flex 和 Grid 替代。浮动会导致父元素高度塌陷,需要清除:
.clearfix::after { content: ""; display: table; clear: both; }
.parent { overflow: hidden; }
多列文本布局(少用):
.article {
column-count: 3;
column-gap: 40px;
column-rule: 1px solid #ddd;
}
视觉表现
颜色表示
.text {
color: #333333; /* HEX */
color: #f00; /* HEX 简写 */
color: rgb(51, 51, 51); /* RGB */
color: rgba(0, 123, 255, 0.5); /* RGBA 带透明度 */
color: hsl(210, 100%, 50%); /* HSL */
color: hsla(210, 100%, 50%, 0.5); /* HSLA */
color: transparent;
}
字体与文本
body {
font-family: "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif;
font-size: 1rem; /* 相对根元素,推荐 */
font-weight: 400;
font-style: italic;
line-height: 1.5; /* 无单位,相对当前字号,推荐 */
text-align: justify;
text-decoration: none;
text-indent: 2em; /* 首行缩进,中文排版常用 */
letter-spacing: 2px;
}
/* font 简写顺序: style variant weight size/line-height family */
.text { font: italic bold 16px/1.5 "Microsoft YaHei", sans-serif; }
/* 文本溢出省略号 */
.truncate { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.text { text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3); }
常用字体分类:衬线体(Times New Roman、Georgia、宋体)、无衬线体(Arial、Helvetica、Microsoft YaHei、黑体)、等宽字体(Consolas、Monaco、Fira Code)、手写体(Comic Sans MS、楷体)。
背景与边框
.box {
background-color: #f5f5f5;
background-image: linear-gradient(to right, #007bff, #00d084);
background-image: radial-gradient(circle, #007bff, #00d084);
background-size: cover; /* cover | contain | 100% 100% */
background-position: center;
background-repeat: no-repeat;
/* 简写: 颜色 图片 重复 位置/大小 */
background: #f5f5f5 url("image.jpg") no-repeat center/cover;
}
.box {
border-radius: 8px; /* 50% 可得圆形 */
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.15);
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1); /* 内阴影 */
}
多重背景时先定义的在上层。
其他视觉属性
.text { opacity: 0.5; } /* 0 时完全透明但仍占据空间 */
.element { cursor: pointer; } /* default | pointer | text | move | not-allowed | help */
.box { overflow: auto; } /* visible | hidden | scroll | auto */
.input { outline: 2px solid #007bff; outline-offset: 2px; }
响应式设计
核心思想是一次设计,到处适用——同一份代码在手机、平板、桌面电脑上都能正常显示。
视口 Meta 标签
<meta name="viewport" content="width=device-width, initial-scale=1.0">
width=device-width:视口宽度等于设备宽度initial-scale=1.0:初始缩放比例为 1user-scalable=no:禁止用户缩放(不推荐,影响可访问性)
没有这个标签,移动端会按桌面宽度渲染再缩小显示,导致文字很小。
媒体查询
@media 媒体类型 and (媒体特性) {
/* 满足条件时应用的 CSS */
}
@media screen and (max-width: 768px) { .container { padding: 10px; } }
/* 范围 */
@media (min-width: 768px) and (max-width: 1024px) { }
/* 屏幕方向 */
@media (orientation: portrait) { } /* 竖屏 */
@media (orientation: landscape) { } /* 横屏 */
/* 高分辨率 */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { }
常用媒体类型:all(默认)、screen、print、speech。
断点与移动优先
移动优先(推荐):先写手机样式,再用 min-width 为大屏幕添加增强样式。
.grid { display: grid; grid-template-columns: 1fr; } /* 手机: 单列 */
@media (min-width: 768px) { .grid { grid-template-columns: repeat(2, 1fr); } } /* 平板 */
@media (min-width: 1024px) { .grid { grid-template-columns: repeat(3, 1fr); } } /* 桌面 */
@media (min-width: 1440px) { .container { max-width: 1400px; } } /* 大桌面 */
桌面优先则相反:先写桌面样式,再用 max-width 为小屏幕覆盖。
响应式单位
- rem: 相对根元素(
<html>)字号,最常用的响应式单位 - em: 相对当前元素字号,适合 padding、margin
- vw / vh: 相对视口宽度/高度,
1vw= 视口宽度的 1% - %: 相对父元素的对应属性
html { font-size: 16px; }
h1 { font-size: 2rem; } /* 32px */
.btn { font-size: 16px; padding: 0.5em 1em; } /* 8px 16px */
.btn-large { font-size: 24px; padding: 0.5em 1em; } /* 12px 24px */
.hero { height: 100vh; width: 100vw; }
.sidebar { width: 25vw; }
注意 vw 包含滚动条宽度,可能导致横向滚动。
响应式图片、表格与排版
img { max-width: 100%; height: auto; display: block; }
.table-wrapper { overflow-x: auto; }
/* clamp() 流体排版 */
h1 { font-size: clamp(1.5rem, 4vw, 3rem); } /* 最小 1.5rem,理想 4vw,最大 3rem */
<picture> 可按屏幕宽度加载不同图片:
<picture>
<source media="(min-width: 1024px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="响应式图片">
</picture>
动画与交互
CSS 提供三种动画方式:Transition(过渡)、Transform(变换)、Animation(关键帧动画)。CSS 动画适合简单的状态变化和装饰性动画,性能更好、代码更简洁;JS 动画适合复杂交互和需要精确控制的场景。
性能提示: 优先使用 transform 和 opacity 做动画,这两个属性不会触发重排(reflow),只触发重绘(repaint)或合成(composite)。
Transition
.element {
transition: property duration timing-function delay;
/* 属性 时长 缓动函数 延迟 */
}
.btn {
background-color: #007bff;
transition: background-color 0.3s ease;
}
.btn:hover { background-color: #0056b3; }
/* 多个过渡 */
.element {
transition:
background-color 0.3s ease,
transform 0.2s ease-in-out,
box-shadow 0.3s ease;
}
transition-timing-function 可选 ease(默认,慢-快-慢)、ease-in、ease-out、ease-in-out、linear 或自定义 cubic-bezier(0.68, -0.55, 0.27, 1.55)。
Transform
.element {
transform: translateX(50px);
transform: translate(-50%, -50%); /* 居中常用 */
transform: rotate(45deg);
transform: scale(1.2);
transform: skewX(15deg);
transform-origin: center; /* 变换原点 */
transform: translateX(50px) rotate(45deg) scale(1.2); /* 顺序很重要 */
}
Animation
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-in {
animation: fadeIn 1s ease-in-out 0.5s infinite alternate forwards;
}
常用属性:animation-duration、animation-timing-function、animation-delay、animation-iteration-count(数字或 infinite)、animation-direction(normal / reverse / alternate / alternate-reverse)、animation-fill-mode(none / forwards / backwards / both)、animation-play-state。
加载动画示例:
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinner {
width: 40px; height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
性能优化
/* ✅ 使用 transform 代替 top/left */
.element {
position: absolute;
transform: translate(200px, 100px);
transition: transform 0.3s;
}
/* 提示浏览器哪些属性即将变化(谨慎使用,动画结束后移除) */
.element { will-change: transform, opacity; }
/* 尊重用户的减少动画设置 */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
同时动画的元素不要太多,移动端应减少动画效果。
工程化
CSS 变量
:root {
--primary-color: #007bff;
--font-size-base: 16px;
--spacing-unit: 8px;
--transition-speed: 0.3s;
}
.btn-primary {
background-color: var(--primary-color);
font-size: var(--font-size-base);
transition: background-color var(--transition-speed);
}
/* 回退值 */
.element { color: var(--text-color, #333); }
/* 局部覆盖 */
.component { --color: red; }
主题切换示例:
:root {
--bg-color: white;
--text-color: #333;
--card-bg: #fff;
--border-color: #ddd;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #e0e0e0;
--card-bg: #2d2d2d;
--border-color: #444;
}
body { background-color: var(--bg-color); color: var(--text-color); }
.card { background-color: var(--card-bg); border: 1px solid var(--border-color); }
BEM 命名法
- Block(块): 独立可复用组件,如
.card、.navbar - Element(元素): 块内部组成,用
__分隔,如.card__title - Modifier(修饰符): 状态或变体,用
--分隔,如.card--featured
<div class="card card--featured">
<img class="card__image" src="image.jpg" alt="图片">
<div class="card__body">
<h3 class="card__title">卡片标题</h3>
<button class="card__btn card__btn--primary">主要按钮</button>
</div>
</div>
优势:可读性强、块可复用、specificity 低(减少冲突)、团队规范统一。
选择器性能
CSS 选择器从右到左匹配,据此可以写出更高效的样式:
/* ❌ 避免过深的选择器 */
div > ul > li > a > span { }
.container * { }
div.container { }
/* ✅ 尽量简短、使用具体类名 */
.nav-link { }
.container .item { }
.container { }
CSS 新特性
容器查询 @container: 根据父容器大小(而非视口)应用样式,是组件级响应式的核心。
.card-container { container-type: inline-size; }
@container (min-width: 400px) { .card { display: flex; flex-direction: row; } }
@container (max-width: 399px) { .card { display: flex; flex-direction: column; } }
层叠层 @layer: 显式控制层叠顺序,解决大型项目样式优先级混乱。
@layer reset, base, components, utilities;
@layer base { body { font-family: sans-serif; } }
@layer components { .btn { padding: 8px 16px; } }
@layer utilities { .text-center { text-align: center; } }
:has() 选择器: 被称为"父选择器",可根据子元素状态设置父元素样式。
.card:has(.badge) { border-color: #007bff; }
form:has(:invalid) { border-color: red; }
h1:has(+ h2) { margin-bottom: 0; }
原生 CSS 嵌套: 类似 Sass/SCSS,但过度嵌套会增加选择器复杂度,建议不超过 3 层。
.card {
border: 1px solid #ddd;
& .title { font-size: 1.25rem; }
&:hover { box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); }
}
常见问题
CSS 和 HTML 是什么关系? HTML 负责页面结构(内容是什么),CSS 负责页面表现(内容长什么样),JS 负责页面行为(内容做什么)。三者配合才能构建完整的网页。
如何理解"移动优先"? 先为移动端(小屏幕)编写基础样式,然后使用 min-width 媒体查询为大屏幕添加增强样式。好处是移动设备加载更快,属于渐进增强。
来源:LearningNotes 学习笔记整理
本文作者
Administrator, 于
发布在 Yui的秘密小屋。
版权协议:
CC BY-NC-SA 4.0,转载请注明出处。
评论
Comments 0 条