选择器
基础选择器
CSS 选择器用于定位 HTML 元素以应用样式。类型选择器匹配元素名称(p、div)。类选择器(.)匹配 class 属性且可重复使用。ID 选择器(#)匹配单个元素且应唯一。通配选择器(*)匹配所有元素。使用逗号分组选择器以共享样式。
/* Type selector - all <p> elements */
p { color: #333; }
/* Class selector - elements with class="btn" */
.btn { padding: 8px 16px; }
/* ID selector - element with id="header" */
#header { background: #fff; }
/* Universal selector - all elements */
* { box-sizing: border-box; }
/* Grouping selector */
h1, h2, h3 { font-family: Arial, sans-serif; }组合器
组合器定义元素之间的关系。后代组合器(空格)匹配任意嵌套元素。子代组合器(>)仅匹配直接子元素。相邻兄弟组合器(+)匹配紧随其后的元素。通用兄弟组合器(~)匹配之后的所有兄弟元素。理解组合器对于无需额外类即可精确设置样式至关重要。
/* Descendant - any <a> inside .nav */
.nav a { text-decoration: none; }
/* Child - direct <li> children of <ul> */
ul > li { list-style: none; }
/* Adjacent sibling - <p> right after <h1> */
h1 + p { font-size: 1.2em; }
/* General sibling - all <p> after <h1> */
h1 ~ p { color: gray; }属性选择器
属性选择器根据属性值匹配元素。[attr] 匹配属性存在。[attr=val] 匹配精确值。^= 匹配前缀,$= 匹配后缀,*= 匹配子串。它们在为表单输入、按类型的链接或带 data 属性的元素设置样式时非常强大,无需添加额外类。
/* Elements with type attribute */
[type] { border: 1px solid #ccc; }
/* Exact match */
[type="text"] { padding: 4px; }
/* Starts with */
a[href^="https"] { color: green; }
/* Ends with */
a[href$=".pdf"] { color: red; }
/* Contains */
a[href*="example"] { font-weight: bold; }伪类
伪类根据状态或位置选择元素。交互类::hover、:focus、:active、:visited、:disabled。结构类::first-child、:last-child、:nth-child(n)、:nth-of-type(n)。:not() 否定选择器。:nth-child(odd/even) 创建斑马条纹。:nth-child(3n) 选择每第 3 个元素。这些减少了额外类的需求。
/* Interactive states */
a:hover { color: red; }
a:visited { color: purple; }
input:focus { border-color: blue; }
input:disabled { background: #eee; }
button:active { transform: scale(0.98); }
/* Structural */
li:first-child { font-weight: bold; }
li:last-child { border: none; }
li:nth-child(odd) { background: #f9f9f9; }
li:nth-child(3n) { color: blue; }
p:not(.highlight) { color: #333; }伪元素
伪元素(::双冒号)为元素的特定部分设置样式。::before 和 ::after 插入生成内容(需要 content 属性)。::first-letter 和 ::first-line 为文本部分设置样式。::selection 为高亮文本设置样式。::placeholder 为输入占位符设置样式。注意:::before/::after 默认是内联的——设置 display:block 以获得块级行为。
/* First line of a paragraph */
p::first-line { font-weight: bold; }
/* First letter (drop cap) */
p::first-letter { font-size: 3em; float: left; }
/* Insert content before/after */
.quote::before { content: "\201C"; }
.quote::after { content: "\201D"; }
/* Selection styling */
::selection { background: yellow; color: black; }
/* Placeholder styling */
input::placeholder { color: #999; }优先级与 !important
优先级决定当选择器冲突时应用哪条规则。内联样式 > ID > 类 > 类型。当优先级相同时,后定义的规则胜出。!important 覆盖一切但会破坏层叠——应避免使用。使用 DevTools 检查优先级。优先使用基于类的选择器以提高可维护性。通过重复类来提高优先级(.btn.btn)是一种 hack——应避免使用。
/* Specificity hierarchy (low to high):
1. Type selectors (p, div) = 0,0,0,1
2. Class selectors (.btn) = 0,0,1,0
3. ID selectors (#header) = 0,1,0,0
4. Inline styles (style="...") = 1,0,0,0
5. !important = overrides all
*/
/* ID beats class */
#nav .link { color: red; } /* wins */
.nav .link { color: blue; }
/* Avoid !important unless necessary */
.critical { color: red !important; }盒模型
外边距与内边距
每个元素都是一个盒子,包含内容、内边距、边框和外边距。内边距在边框内部(影响背景),外边距在外部(透明)。简写:1 个值 = 所有边,2 个值 = 上/下 左/右,3 个 = 上 左/右 下,4 个 = 上 右 下 左(顺时针)。margin: 0 auto 使具有定义宽度的块级元素水平居中。
.box {
/* TRBL: top right bottom left */
margin: 10px 20px 10px 20px;
/* Shorthand: top/bottom left/right */
margin: 10px 20px;
/* All sides */
padding: 15px;
/* Individual sides */
margin-top: 0;
padding-left: 24px;
/* Center horizontally (block) */
margin: 0 auto;
}边框与轮廓
border 在内边距周围添加线条,影响布局。outline 在边框外部绘制且不影响布局——适用于焦点指示器。border-radius 圆角(单个值或每个角:左上 右上 右下 左下)。outline-offset 在边框和轮廓之间添加间距。始终为可访问性提供可见的焦点样式。
.box {
/* Shorthand: width style color */
border: 2px solid #333;
/* Individual sides */
border-bottom: 3px dashed red;
border-radius: 8px;
/* Outline (doesn't affect layout) */
outline: 2px solid blue;
outline-offset: 4px;
}
/* Remove default focus, add custom */
button:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(0,123,255,0.5);
}盒尺寸
box-sizing: content-box(默认)表示 width/height 仅应用于内容——内边距和边框会增加总尺寸。box-sizing: border-box 将内边距和边框包含在 width/height 中,使尺寸可预测。始终全局设置 border-box 以获得一致的布局。这是最重要的 CSS 重置之一。
/* Default: width = content only */
.content-box {
box-sizing: content-box;
width: 200px;
padding: 20px;
border: 5px solid;
/* Total width: 200 + 40 + 10 = 250px */
}
/* Recommended: width includes padding+border */
.border-box {
box-sizing: border-box;
width: 200px;
padding: 20px;
border: 5px solid;
/* Total width: 200px */
}
/* Apply globally */
*, *::before, *::after {
box-sizing: border-box;
}盒阴影
box-shadow 添加阴影效果:offset-x offset-y blur-radius spread-radius color。正偏移将阴影向右/下移动。inset 创建内阴影。多个阴影分层(第一个 = 顶层)。使用 rgba 创建自然融合的半透明阴影。阴影非常适合营造深度,但过度使用会损害性能——优先使用细微的阴影。
/* offset-x offset-y blur spread color */
.card {
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
/* Multiple shadows */
.button {
box-shadow:
0 1px 2px rgba(0,0,0,0.1),
0 4px 8px rgba(0,0,0,0.05);
}
/* Inset shadow */
.input:focus {
box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}
/* No shadow */
.no-shadow { box-shadow: none; }显示与可见性
display: none 将元素从布局中完全移除(不占空间)。visibility: hidden 隐藏元素但保留其空间。opacity: 0 使其透明但仍可交互。block 元素占据全部宽度并换行。inline 元素随文本流动。inline-block 结合了内联流动和块级尺寸(width、height)。使用 display: none 切换内容。
/* Display types */
div { display: block; } /* full width, line break */
span { display: inline; } /* content width, no break */
.inline-block { display: inline-block; } /* inline but block props */
.flex { display: flex; } /* flex container */
.grid { display: grid; } /* grid container */
.none { display: none; } /* removed from layout */
/* Visibility (keeps space) */
.hidden { visibility: hidden; }
/* Opacity (keeps space, can interact) */
.fade { opacity: 0; }颜色与单位
颜色格式
CSS 支持多种颜色格式。Hex(#rrggbb)最常见。RGB/RGBA 添加 alpha 透明度。HSL(色相 0-360,饱和度%,亮度%)很直观——改变色相切换颜色,改变亮度调整明暗。currentColor 继承元素的 color 属性。现代 CSS 还支持 oklch() 和 color() 以获得更宽的色域。使用 rgba/hsla 实现透明度。
/* Named colors */
.color { color: red; background: tomato; }
/* Hexadecimal */
.hex { color: #ff6600; } /* 6-digit */
.hex-short { color: #f60; } /* 3-digit shorthand */
/* RGB / RGBA */
.rgb { color: rgb(255, 102, 0); }
.rgba { background: rgba(0, 0, 0, 0.5); }
/* HSL / HSLA (hue, saturation, lightness) */
.hsl { color: hsl(20, 100%, 50%); }
.hsla { background: hsla(120, 100%, 50%, 0.3); }
/* Current color keyword */
.box { color: blue; border: 2px solid currentColor; }长度单位
px 是绝对且可预测的。em 相对于父元素的 font-size(嵌套时会叠加)。rem 相对于根(html)元素的 font-size——一致且更适合可访问性。% 相对于父元素。vh/vw 相对于视口(100vh = 全高)。使用 rem 设置字体大小,% 用于布局,px 用于边框/精细细节。
/* Absolute units */
.px { font-size: 16px; } /* 1px = 1/96 inch */
.pt { font-size: 12pt; } /* 1pt = 1/72 inch */
/* Relative to parent font-size */
.em { font-size: 1.5em; } /* 1.5x parent */
/* Relative to root font-size (html) */
.rem { font-size: 1.2rem; } /* 1.2x root (usually 16px) */
/* Relative to parent dimensions */
.pct { width: 50%; } /* 50% of parent */
/* Viewport units */
.vh { height: 100vh; } /* 100% of viewport height */
.vw { width: 50vw; } /* 50% of viewport width */
.vmin { font-size: 2vmin; } /* 2% of smaller dimension */CSS 函数
calc() 执行混合单位的数学运算(例如 100% - 250px)。min() 选择最小值(非常适合响应式最大宽度)。max() 选择最大值。clamp(min, preferred, max) 创建在边界之间缩放的流式值——非常适合响应式排版。var() 引用自定义属性并带有可选回退值。这些函数使 CSS 无需媒体查询即可实现动态效果。
/* calc() - mathematical calculations */
.sidebar { width: calc(100% - 250px); }
.gap { margin: calc(1rem + 10px); }
/* min() / max() - choose smaller/larger */
.responsive { width: min(90%, 1200px); }
.min-width { width: max(300px, 50%); }
/* clamp() - fluid sizing with bounds */
.title { font-size: clamp(1.5rem, 4vw, 3rem); }
/* var() - use custom properties */
.btn { color: var(--primary, #007bff); }渐变
渐变创建平滑的颜色过 渡。linear-gradient(direction, color1, color2) 沿方向(to right、45deg)变化。radial-gradient 从中心点向外扩展。conic-gradient 围绕中心旋转。可以添加带位置的颜色停止点:linear-gradient(to right, red 0%, blue 50%, green 100%)。渐变是图像而非颜色,可在任何接受 background-image 的地方使用。
/* Linear gradient */
.bg1 {
background: linear-gradient(to right, #ff0000, #0000ff);
}
/* Diagonal with angle */
.bg2 {
background: linear-gradient(45deg, #ff0000, #00ff00, #0000ff);
}
/* Radial gradient */
.bg3 {
background: radial-gradient(circle, #ff0000, #0000ff);
}
/* Conic gradient */
.bg4 {
background: conic-gradient(red, yellow, green, blue, red);
}滤镜与混合模式
filter 应用视觉效果:blur()、brightness()、contrast()、grayscale()、sepia()、hue-rotate()、invert()、opacity()、saturate()。多个滤镜可链式组合。mix-blend-mode 将元素与其后面的内容混合(multiply、screen、overlay 等)。backdrop-filter 对元素后面的区域应用滤镜(非常适合毛玻璃效果)。滤镜可能影响性能——谨慎使用。
/* Filters */
img.bw { filter: grayscale(100%); }
img.blur { filter: blur(5px); }
img.bright { filter: brightness(1.5); }
img.sepia { filter: sepia(0.8); }
/* Multiple filters */
img.vintage {
filter: sepia(0.5) contrast(1.2) brightness(0.9);
}
/* Blend mode */
.overlay {
background: rgba(255,0,0,0.5);
mix-blend-mode: multiply;
}排版
字体属性
font-family 接受回退列表——浏览器使用第一个可用的字体。始终以通用字体系列结尾(serif、sans-serif、monospace)。font-weight 范围从 100(细)到 900(粗)。line-height: 1.5 表示 1.5 倍字体大小——1.4-1.6 最适合正文可读性。font 简写必须至少包含 size 和 family。
body {
/* Font shorthand: style weight size/line-height family */
font: italic bold 16px/1.5 Arial, sans-serif;
/* Individual properties */
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 16px;
font-weight: 400; /* 100-900, normal=400, bold=700 */
font-style: italic; /* normal, italic, oblique */
line-height: 1.5;
}文本样式
text-align 控制水平对齐。text-decoration 添加线条(下划线、上划线、删除线)。text-transform 改变大小写。letter-spacing(字距)和 word-spacing 调整字符和单词之间的间距。white-space: nowrap 防止文本换行。对于垂直对齐,使用 vertical-align(内联)或 flexbox/grid 对齐(块级)。
p {
text-align: justify; /* left, right, center, justify */
text-decoration: underline; /* none, overline, line-through */
text-transform: capitalize; /* uppercase, lowercase, capitalize */
text-indent: 2em; /* indent first line */
letter-spacing: 0.05em; /* tracking */
word-spacing: 0.1em;
white-space: nowrap; /* prevent wrapping */
}
a {
text-decoration: none;
color: #0066cc;
}文本溢出与换行
要用省略号截断文本,需要三个属性:white-space: nowrap、overflow: hidden 和 text-overflow: ellipsis。overflow-wrap: break-word 断开长单词以防止溢出。word-break: break-all 在任意字符处断开。text-wrap: balance(较新)平衡标题的行长度。始终设置 max-width 或 width 才能使截断生效。
/* Truncate with ellipsis */
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
/* Break long words */
.break-word {
overflow-wrap: break-word;
word-break: break-all;
}
/* Balance text wrapping (newer) */
h1 {
text-wrap: balance;
}Web 字体(@font-face)
@font-face 加载自定义字体。woff2 是现代格式(最佳压缩)。提供 woff 作为回退。font-display: swap 立即显示回退文本,然后在字体加载后替换(防止不可见文本)。始终声明回退字体系列。Google Fonts 通过 @import 或 <link> 提供托管字体。预加载关键字体以提高性能。