跳到主要内容

CSS3 新特性全面解析

概述

CSS3 是 CSS(层叠样式表)的第三个主要版本,它引入了大量强大的新特性,让前端开发者能够实现以前只能通过 JavaScript 或图片才能做到的效果。从圆角、阴影到动画、变换,CSS3 极大地丰富了网页的视觉表现力。

为什么要学 CSS3? 现代网页几乎离不开 CSS3。掌握它不仅能大幅提升页面的视觉效果和用户体验,还能减少对 JavaScript 和图片的依赖,从而提升性能。CSS3 也是前端面试的高频考点。


一、选择器增强

CSS3 新增了许多强大的选择器,让我们能更精准地定位元素。

1.1 属性选择器

/* 选择 href 以 https 开头的链接 */
a[href^="https"] {
color: green;
}

/* 选择 href 以 .pdf 结尾的链接 */
a[href$=".pdf"] {
color: red;
}

/* 选择 class 中包含 "btn" 的元素 */
div[class*="btn"] {
cursor: pointer;
}
选择器含义示例
[attr^=val]属性值以 val 开头a[href^="https"]
[attr$=val]属性值以 val 结尾a[href$=".pdf"]
[attr*=val]属性值包含 valdiv[class*="btn"]

1.2 结构伪类选择器

这是 CSS3 中最实用的选择器家族之一,可以根据元素在 DOM 结构中的位置来选择。

/* 第一个子元素 */
li:first-child {
font-weight: bold;
}

/* 最后一个子元素 */
li:last-child {
border-bottom: none;
}

/* 第 n 个子元素(从 1 开始计数) */
li:nth-child(3) {
color: red;
}

/* 偶数行(常用于表格斑马纹) */
tr:nth-child(even) {
background-color: #f2f2f2;
}

/* 奇数行 */
tr:nth-child(odd) {
background-color: #ffffff;
}

/* 每 3 个元素中的第 1 个 */
li:nth-child(3n+1) {
color: blue;
}

/* 唯一子元素 */
p:only-child {
font-style: italic;
}
小技巧

nth-child 的参数是一个公式 an+b

  • 2n 等于 even(偶数)
  • 2n+1 等于 odd(奇数)
  • 3n 表示第 3、6、9... 个元素
  • -n+3 表示前 3 个元素

1.3 伪元素选择器

CSS3 规范要求伪元素使用双冒号 :: 来区分伪类(单冒号 :),不过浏览器也兼容单冒号写法。

/* 在元素内容前插入 */
.quote::before {
content: "\201C"; /* 左双引号 */
font-size: 2em;
color: #ccc;
}

/* 在元素内容后插入 */
.quote::after {
content: "\201D"; /* 右双引号 */
font-size: 2em;
color: #ccc;
}

/* 选中文本的样式 */
::selection {
background-color: #b3d4fc;
color: #333;
}

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

1.4 其他实用伪类

/* 否定伪类:选择不是 .special 的段落 */
p:not(.special) {
color: #333;
}

/* 空元素 */
div:empty {
display: none;
}

/* 目标伪类:当 URL 锚点匹配时 */
#section1:target {
background-color: #ffffcc;
}

/* 表单相关伪类 */
input:focus {
border-color: #4a90d9;
outline: none;
}

input:disabled {
opacity: 0.5;
cursor: not-allowed;
}

input:checked + label {
font-weight: bold;
}

二、边框与圆角

2.1 border-radius(圆角)

CSS3 之前,实现圆角需要用图片拼接,非常麻烦。现在只需一行代码。

/* 四个角相同 */
.box {
border-radius: 10px;
}

/* 分别设置四个角:左上 右上 右下 左下 */
.box {
border-radius: 10px 20px 30px 40px;
}

/* 圆形(正方形元素 + 50% 圆角) */
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
}

/* 胶囊形状 */
.capsule {
width: 200px;
height: 50px;
border-radius: 25px; /* 高度的一半 */
}

/* 椭圆圆角(水平 / 垂直) */
.ellipse {
border-radius: 50px / 25px;
}

2.2 box-shadow(盒子阴影)

/* 基础阴影:水平偏移 垂直偏移 模糊半径 颜色 */
.shadow {
box-shadow: 2px 4px 8px rgba(0, 0, 0, 0.2);
}

/* 扩展半径 */
.shadow-spread {
box-shadow: 2px 4px 8px 2px rgba(0, 0, 0, 0.2);
}

/* 内阴影 */
.inner-shadow {
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2);
}

/* 多重阴影 */
.multi-shadow {
box-shadow:
0 2px 4px rgba(0, 0, 0, 0.1),
0 8px 16px rgba(0, 0, 0, 0.1);
}

/* 无偏移阴影(发光效果) */
.glow {
box-shadow: 0 0 15px rgba(66, 133, 244, 0.6);
}

2.3 border-image(边框图片)

.fancy-border {
border: 15px solid transparent;
border-image-source: url('border.png');
border-image-slice: 30;
border-image-repeat: round;
}

/* 简写形式 */
.fancy-border {
border: 15px solid transparent;
border-image: url('border.png') 30 round;
}

三、背景增强

3.1 多重背景

CSS3 允许为一个元素设置多个背景图片,它们会按顺序叠加(先声明的在最上层)。

.multi-bg {
background-image:
url('top-layer.png'),
url('middle-layer.png'),
url('bottom-layer.png');
background-position:
top right,
center center,
bottom left;
background-repeat:
no-repeat,
no-repeat,
repeat;
}

3.2 background-size

/* 指定具体大小 */
.bg {
background-size: 200px 100px;
}

/* 覆盖整个容器(可能裁剪) */
.bg-cover {
background-size: cover;
}

/* 完整显示(可能有留白) */
.bg-contain {
background-size: contain;
}
cover vs contain
  • cover:图片缩放以完全覆盖容器,可能有部分被裁剪。适合做背景大图。
  • contain:图片缩放以完整显示,容器可能有留白。适合需要展示完整图片的场景。

3.3 background-origin 和 background-clip

/* background-origin:背景图片的定位参考区域 */
.box {
background-origin: border-box; /* 从边框区域开始 */
background-origin: padding-box; /* 从内边距区域开始(默认) */
background-origin: content-box; /* 从内容区域开始 */
}

/* background-clip:背景的绘制区域 */
.box {
background-clip: border-box; /* 背景延伸到边框(默认) */
background-clip: padding-box; /* 背景延伸到内边距 */
background-clip: content-box; /* 背景仅覆盖内容区域 */
}

/* 文字镂空效果 */
.text-clip {
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 48px;
font-weight: bold;
}

四、渐变(Gradient)

渐变是 CSS3 中最实用的特性之一,它让我们不需要图片就能创建丰富的色彩过渡效果。

4.1 线性渐变

/* 从上到下(默认) */
.gradient {
background: linear-gradient(#ff6b6b, #4ecdc4);
}

/* 指定方向 */
.gradient-right {
background: linear-gradient(to right, #ff6b6b, #4ecdc4);
}

/* 指定角度 */
.gradient-angle {
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
}

/* 多色渐变 */
.gradient-multi {
background: linear-gradient(to right, #ff6b6b, #feca57, #48dbfb, #ff9ff3);
}

/* 控制颜色位置 */
.gradient-stop {
background: linear-gradient(to right, #ff6b6b 0%, #ff6b6b 50%, #4ecdc4 50%, #4ecdc4 100%);
}

4.2 径向渐变

/* 默认从中心向外扩散 */
.radial {
background: radial-gradient(#ff6b6b, #4ecdc4);
}

/* 指定形状和大小 */
.radial-circle {
background: radial-gradient(circle at center, #ff6b6b, #4ecdc4);
}

/* 椭圆渐变 + 位置偏移 */
.radial-ellipse {
background: radial-gradient(ellipse at top left, #ff6b6b, #4ecdc4);
}

4.3 锥形渐变

/* 色轮效果 */
.conic {
background: conic-gradient(red, yellow, green, blue, red);
border-radius: 50%;
}

/* 饼图效果 */
.pie {
background: conic-gradient(
#ff6b6b 0% 30%,
#4ecdc4 30% 65%,
#feca57 65% 100%
);
border-radius: 50%;
}

4.4 重复渐变

/* 重复线性渐变(条纹效果) */
.stripes {
background: repeating-linear-gradient(
45deg,
#ff6b6b,
#ff6b6b 10px,
#fff 10px,
#fff 20px
);
}

/* 重复径向渐变(同心圆效果) */
.concentric {
background: repeating-radial-gradient(
circle,
#ff6b6b,
#ff6b6b 10px,
#fff 10px,
#fff 20px
);
}

五、文本效果

5.1 text-shadow(文字阴影)

/* 基础阴影 */
.shadow-text {
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

/* 多重阴影(发光效果) */
.glow-text {
text-shadow:
0 0 10px #fff,
0 0 20px #fff,
0 0 30px #e60073,
0 0 40px #e60073;
}

/* 浮雕效果 */
.emboss-text {
color: #ccc;
text-shadow:
-1px -1px 0 #fff,
1px 1px 0 #333;
}

5.2 文本溢出处理

/* 单行文本溢出省略 */
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

/* 多行文本溢出省略(Webkit 内核) */
.multi-ellipsis {
display: -webkit-box;
-webkit-line-clamp: 3; /* 限制为 3 行 */
-webkit-box-orient: vertical;
overflow: hidden;
}

5.3 word-wrap 和 word-break

/* 长单词换行(不截断单词) */
.wrap {
overflow-wrap: break-word; /* 新标准名称 */
word-wrap: break-word; /* 旧名称,兼容性更好 */
}

/* 强制在任意字符处换行 */
.break-all {
word-break: break-all;
}

5.4 @font-face(自定义字体)

/* 定义自定义字体 */
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap; /* 字体加载策略 */
}

/* 使用自定义字体 */
body {
font-family: 'MyFont', sans-serif;
}
font-display 的值
行为
auto由浏览器决定
block短时间隐藏文本,然后显示自定义字体
swap立即显示后备字体,加载完成后切换(推荐)
fallback极短时间隐藏,之后显示后备字体,仅在很快加载完时切换
optional极短时间隐藏,然后显示后备字体,浏览器自行决定是否切换

六、2D 变换(Transform)

CSS3 的 transform 属性可以对元素进行位移、缩放、旋转、倾斜等操作,而不影响文档流

6.1 基本变换

/* 位移 */
.translate {
transform: translate(50px, 30px); /* X 轴 50px, Y 轴 30px */
transform: translateX(50px); /* 仅 X 轴 */
transform: translateY(30px); /* 仅 Y 轴 */
}

/* 缩放 */
.scale {
transform: scale(1.5); /* 整体放大 1.5 倍 */
transform: scale(2, 0.5); /* X 轴 2 倍,Y 轴 0.5 倍 */
transform: scaleX(2); /* 仅 X 轴 */
}

/* 旋转 */
.rotate {
transform: rotate(45deg); /* 顺时针旋转 45 度 */
transform: rotate(-30deg); /* 逆时针旋转 30 度 */
}

/* 倾斜 */
.skew {
transform: skew(20deg, 10deg); /* X 轴 20 度,Y 轴 10 度 */
transform: skewX(20deg); /* 仅 X 轴 */
}

6.2 组合变换

/* 多个变换可以组合使用(注意顺序会影响最终效果) */
.combined {
transform: translate(50px, 0) rotate(45deg) scale(1.2);
}
变换顺序很重要

translate(100px, 0) rotate(45deg)rotate(45deg) translate(100px, 0) 的效果完全不同!变换是从右向左依次应用的。先旋转再平移,会沿旋转后的坐标轴方向移动。

6.3 transform-origin(变换原点)

/* 默认原点在元素中心 */
.box {
transform-origin: center center; /* 默认值 */
}

/* 改变原点 */
.box {
transform-origin: top left; /* 左上角 */
transform-origin: 0 0; /* 等价于 top left */
transform-origin: 50% 100%; /* 底部中心 */
transform: rotate(45deg);
}

七、3D 变换

CSS3 不仅支持 2D 变换,还支持在三维空间中操作元素。

7.1 基础 3D 变换

/* 3D 位移 */
.translate3d {
transform: translate3d(50px, 30px, 100px); /* X, Y, Z */
transform: translateZ(100px); /* 仅 Z 轴 */
}

/* 3D 旋转 */
.rotate3d {
transform: rotateX(45deg); /* 绕 X 轴旋转(翻转效果) */
transform: rotateY(45deg); /* 绕 Y 轴旋转(翻页效果) */
transform: rotateZ(45deg); /* 绕 Z 轴旋转(同 2D rotate) */
}

/* 3D 缩放 */
.scale3d {
transform: scale3d(1.5, 1.5, 1.5);
transform: scaleZ(2);
}

7.2 透视(perspective)

要看到 3D 效果,必须设置透视。透视就像我们的眼睛,值越小"离得越近",3D 效果越明显。

/* 在父元素上设置透视(推荐) */
.container {
perspective: 800px; /* 观察距离 */
perspective-origin: center; /* 观察位置 */
}

/* 在元素本身设置透视 */
.box {
transform: perspective(800px) rotateY(45deg);
}

7.3 transform-style

/* 开启 3D 空间,让子元素在三维空间中呈现 */
.container {
transform-style: preserve-3d;
}

7.4 backface-visibility

/* 翻转卡片时隐藏背面 */
.card-front,
.card-back {
backface-visibility: hidden;
}

翻转卡片完整示例

.card {
width: 200px;
height: 300px;
perspective: 1000px;
}

.card-inner {
position: relative;
width: 100%;
height: 100%;
transition: transform 0.6s;
transform-style: preserve-3d;
}

.card:hover .card-inner {
transform: rotateY(180deg);
}

.card-front,
.card-back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
border-radius: 10px;
}

.card-front {
background: #4ecdc4;
}

.card-back {
background: #ff6b6b;
transform: rotateY(180deg);
}
<div class="card">
<div class="card-inner">
<div class="card-front">正面内容</div>
<div class="card-back">背面内容</div>
</div>
</div>

八、过渡(Transition)

过渡让 CSS 属性的变化不再是瞬间完成,而是在一段时间内平滑过渡,实现简单的动画效果。

8.1 基本用法

.btn {
background-color: #4ecdc4;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;

/* 过渡设置 */
transition: background-color 0.3s ease;
}

.btn:hover {
background-color: #45b7aa;
}

8.2 多属性过渡

.card {
/* 分别设置不同属性的过渡 */
transition:
transform 0.3s ease,
box-shadow 0.3s ease,
background-color 0.5s ease;
}

.card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
background-color: #f9f9f9;
}

/* 所有属性统一过渡(简便但不推荐用于生产) */
.box {
transition: all 0.3s ease;
}

8.3 缓动函数(timing-function)

.box {
/* 内置缓动函数 */
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.68, -0.55, 0.265, 1.55);

/* 步进函数 */
transition-timing-function: steps(4, end);
}
哪些属性可以过渡?

并非所有 CSS 属性都支持过渡。一般来说,有数值中间值的属性都可以过渡:

  • 可以过渡:widthheightopacitycolortransformmarginpaddingborder-width
  • 不能过渡:displayfont-familyposition

九、动画(Animation)

与过渡不同,动画可以定义多个关键帧,实现更复杂的动画序列,而且可以自动播放,不需要触发事件。

9.1 @keyframes 定义关键帧

/* 使用 from/to */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}

/* 使用百分比(多个关键帧) */
@keyframes bounce {
0% { transform: translateY(0); }
25% { transform: translateY(-30px); }
50% { transform: translateY(0); }
75% { transform: translateY(-15px); }
100% { transform: translateY(0); }
}

9.2 应用动画

.element {
/* 简写形式 */
animation: fadeIn 0.5s ease-out forwards;

/* 完整写法 */
animation-name: fadeIn;
animation-duration: 0.5s;
animation-timing-function: ease-out;
animation-delay: 0s;
animation-iteration-count: 1; /* infinite 为无限循环 */
animation-direction: normal; /* alternate 为来回 */
animation-fill-mode: forwards; /* 保持结束状态 */
animation-play-state: running; /* paused 为暂停 */
}

9.3 animation 各属性详解

属性说明
animation-name关键帧名称对应 @keyframes 的名称
animation-duration时间一次动画的持续时间
animation-timing-function缓动函数同过渡的缓动函数
animation-delay时间动画开始前的延迟
animation-iteration-count数字 / infinite播放次数
animation-directionnormal / reverse / alternate / alternate-reverse播放方向
animation-fill-modenone / forwards / backwards / both动画前后状态保持
animation-play-staterunning / paused播放/暂停控制

9.4 实用动画示例

/* 旋转加载指示器 */
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}

.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #4ecdc4;
border-radius: 50%;
animation: spin 1s linear infinite;
}

/* 脉冲效果 */
@keyframes pulse {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.05); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}

.pulse {
animation: pulse 2s ease-in-out infinite;
}

/* 打字机效果 */
@keyframes typing {
from { width: 0; }
to { width: 100%; }
}

@keyframes blink {
50% { border-color: transparent; }
}

.typewriter {
overflow: hidden;
white-space: nowrap;
border-right: 3px solid #333;
animation:
typing 3s steps(30) forwards,
blink 0.75s step-end infinite;
}

十、Flexbox 弹性布局

Flexbox 是 CSS3 引入的一维布局方案,专为解决元素在容器中的对齐、分布和排列而设计。

10.1 核心概念

.container {
display: flex; /* 块级弹性容器 */
/* 或 */
display: inline-flex; /* 行内弹性容器 */
}

10.2 容器属性

.container {
display: flex;

/* 主轴方向 */
flex-direction: row; /* 水平(默认) */
flex-direction: column; /* 垂直 */
flex-direction: row-reverse; /* 水平反向 */
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; /* 基线对齐 */

/* 间距(CSS3 后期新增,替代 margin hack) */
gap: 16px; /* 行列间距相同 */
gap: 10px 20px; /* 行间距 列间距 */
}

10.3 项目属性

.item {
/* flex 简写(推荐) */
flex: 1; /* 等价于 flex: 1 1 0% */
flex: auto; /* 等价于 flex: 1 1 auto */
flex: none; /* 等价于 flex: 0 0 auto */
flex: 0 0 200px; /* 不放大、不缩小、固定 200px */

/* 单独设置 */
flex-grow: 1; /* 放大比例,0 不放大(默认) */
flex-shrink: 1; /* 缩小比例,0 不缩小 */
flex-basis: 200px; /* 主轴基础尺寸 */

/* 排列顺序 */
order: -1; /* 数值越小越靠前,默认 0 */

/* 单独对齐(覆盖 align-items) */
align-self: center;
}

10.4 经典布局示例

/* 水平垂直居中 */
.center {
display: flex;
justify-content: center;
align-items: center;
}

/* 固定头尾、内容自适应 */
.layout {
display: flex;
flex-direction: column;
height: 100vh;
}
.header, .footer { flex: none; }
.main { flex: 1; }

/* 等宽分栏 */
.row {
display: flex;
gap: 16px;
}
.col { flex: 1; }

/* 圣杯布局 */
.holy-grail {
display: flex;
}
.left, .right { flex: 0 0 200px; }
.center-content { flex: 1; }

十一、媒体查询(Media Queries)

媒体查询是实现响应式设计的核心机制,让同一份代码能适配不同设备。

11.1 基本语法

/* 屏幕宽度小于 768px 时(移动端) */
@media screen and (max-width: 768px) {
.container {
flex-direction: column;
padding: 10px;
}
}

/* 屏幕宽度在 768px 到 1024px 之间(平板) */
@media screen and (min-width: 768px) and (max-width: 1024px) {
.container {
max-width: 960px;
}
}

/* 打印样式 */
@media print {
.no-print {
display: none;
}
}

11.2 常用断点

/* 移动优先策略(推荐) */
/* 默认样式 = 移动端样式 */
.container {
padding: 10px;
}

/* 平板 */
@media (min-width: 768px) {
.container {
padding: 20px;
max-width: 720px;
}
}

/* 笔记本 */
@media (min-width: 1024px) {
.container {
max-width: 960px;
}
}

/* 桌面 */
@media (min-width: 1280px) {
.container {
max-width: 1200px;
}
}

11.3 CSS3 新增媒体特性

/* 暗色模式偏好 */
@media (prefers-color-scheme: dark) {
body {
background: #1a1a2e;
color: #eee;
}
}

/* 减少动画偏好(无障碍) */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}

/* 悬浮能力检测 */
@media (hover: hover) {
.btn:hover {
background: #45b7aa;
}
}

/* 高分辨率屏幕 */
@media (min-resolution: 2dppx) {
.logo {
background-image: url('logo@2x.png');
}
}

十二、CSS 自定义属性(CSS 变量)

CSS 变量让我们可以在样式表中定义可复用的值,大大提升了代码的可维护性。

12.1 基本使用

/* 定义变量(通常在 :root 中定义全局变量) */
:root {
--primary-color: #4ecdc4;
--secondary-color: #ff6b6b;
--font-size-base: 16px;
--spacing-unit: 8px;
--border-radius: 4px;
}

/* 使用变量 */
.btn {
background-color: var(--primary-color);
font-size: var(--font-size-base);
padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
border-radius: var(--border-radius);
}

/* 提供默认值 */
.box {
color: var(--text-color, #333); /* 如果 --text-color 未定义,使用 #333 */
}

12.2 作用域与继承

:root {
--color: blue; /* 全局变量 */
}

.card {
--color: green; /* 局部变量,仅在 .card 及其子元素内生效 */
}

.text {
color: var(--color); /* 在 .card 内为 green,其他地方为 blue */
}

12.3 结合 JavaScript

// 读取 CSS 变量
const root = document.documentElement;
const color = getComputedStyle(root).getPropertyValue('--primary-color');

// 设置 CSS 变量
root.style.setProperty('--primary-color', '#ff6b6b');

12.4 实现主题切换

/* 浅色主题(默认) */
:root {
--bg-color: #ffffff;
--text-color: #333333;
--card-bg: #f5f5f5;
--border-color: #e0e0e0;
}

/* 深色主题 */
[data-theme="dark"] {
--bg-color: #1a1a2e;
--text-color: #e0e0e0;
--card-bg: #16213e;
--border-color: #0f3460;
}

/* 使用变量 */
body {
background-color: var(--bg-color);
color: var(--text-color);
}

.card {
background: var(--card-bg);
border: 1px solid var(--border-color);
}
// 切换主题
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
document.documentElement.setAttribute(
'data-theme',
current === 'dark' ? 'light' : 'dark'
);
}

十三、多列布局(Multi-column)

多列布局让我们可以像报纸一样将内容分成多栏显示。

.newspaper {
/* 指定列数 */
column-count: 3;

/* 或指定列宽(自动计算列数) */
column-width: 250px;

/* 列间距 */
column-gap: 30px;

/* 列分隔线 */
column-rule: 1px solid #ddd;
}

/* 跨列元素 */
.newspaper h2 {
column-span: all; /* 标题横跨所有列 */
}

/* 防止内容被截断 */
.newspaper p {
break-inside: avoid;
}

十四、滤镜(Filter)

CSS3 滤镜让我们可以像 Photoshop 一样对元素应用视觉效果。

/* 模糊 */
.blur {
filter: blur(5px);
}

/* 亮度 */
.brightness {
filter: brightness(1.5); /* 150% 亮度 */
}

/* 对比度 */
.contrast {
filter: contrast(200%);
}

/* 灰度 */
.grayscale {
filter: grayscale(100%);
}

/* 色相旋转 */
.hue-rotate {
filter: hue-rotate(90deg);
}

/* 反色 */
.invert {
filter: invert(100%);
}

/* 饱和度 */
.saturate {
filter: saturate(200%);
}

/* 深褐色调(怀旧) */
.sepia {
filter: sepia(100%);
}

/* 投影(类似 box-shadow,但跟随元素形状) */
.drop-shadow {
filter: drop-shadow(4px 4px 8px rgba(0, 0, 0, 0.3));
}

/* 组合滤镜 */
.vintage {
filter: sepia(60%) contrast(110%) brightness(90%) saturate(80%);
}

毛玻璃效果(backdrop-filter)

.glass {
background: rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px); /* Safari 兼容 */
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 16px;
}

十五、其他实用特性

15.1 calc() 函数

/* 动态计算 */
.sidebar {
width: 250px;
}
.content {
width: calc(100% - 250px); /* 减去侧边栏宽度 */
padding: calc(16px + 1vw); /* 混合单位计算 */
font-size: calc(14px + 0.5vw); /* 响应式字体 */
}

15.2 视口单位

.hero {
height: 100vh; /* 视口高度 */
width: 100vw; /* 视口宽度 */
font-size: 5vmin; /* 视口宽高较小值的 5% */
}

/* 新单位(解决移动端地址栏问题) */
.full-height {
height: 100dvh; /* 动态视口高度 */
height: 100svh; /* 小视口高度 */
height: 100lvh; /* 大视口高度 */
}

15.3 object-fit(替换元素适配)

.img-cover {
width: 300px;
height: 200px;
object-fit: cover; /* 覆盖,可能裁剪 */
}

.img-contain {
object-fit: contain; /* 完整显示 */
}

.img-fill {
object-fit: fill; /* 拉伸填充(可能变形) */
}

.img-none {
object-fit: none; /* 保持原始尺寸 */
}

/* 配合 object-position 调整位置 */
.img-top {
object-fit: cover;
object-position: top center;
}

15.4 scroll-behavior(平滑滚动)

/* 全局平滑滚动 */
html {
scroll-behavior: smooth;
}

15.5 滚动捕捉(Scroll Snap)

.carousel {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}

.slide {
flex: 0 0 100%;
scroll-snap-align: start;
}

15.6 accent-color(表单控件着色)

/* 一行代码美化表单控件 */
:root {
accent-color: #4ecdc4;
}

15.7 容器查询(Container Queries)

容器查询是 CSS 中的一个重要新特性,它允许根据父容器的尺寸而不是视口尺寸来应用样式。

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

/* 根据容器宽度调整样式 */
@container card (min-width: 400px) {
.card {
display: flex;
gap: 16px;
}
}

@container card (max-width: 399px) {
.card {
display: block;
}

.card img {
width: 100%;
}
}

15.8 CSS 嵌套(Nesting)

原生 CSS 现在支持嵌套语法,类似 Sass/Less。

.card {
background: white;
border-radius: 8px;

& .title {
font-size: 1.5rem;
color: #333;
}

& .body {
padding: 16px;
}

&:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
padding: 12px;
}
}

十六、CSS3 属性速查表

分类属性用途
边框border-radius圆角
box-shadow盒子阴影
border-image边框图片
背景background-size背景尺寸
background-origin背景定位区域
background-clip背景绘制区域
多重背景多个背景图叠加
渐变linear-gradient线性渐变
radial-gradient径向渐变
conic-gradient锥形渐变
文本text-shadow文字阴影
text-overflow文本溢出处理
word-wrap长单词换行
@font-face自定义字体
变换transform2D/3D 变换
transform-origin变换原点
perspective透视
过渡transition属性过渡动画
动画@keyframes定义关键帧
animation应用动画
布局display: flex弹性布局
display: grid网格布局
column-count多列布局
响应式@media媒体查询
vw / vh视口单位
函数calc()动态计算
var()CSS 变量
视觉filter滤镜效果
backdrop-filter背景滤镜
object-fit替换元素适配
现代特性@container容器查询
CSS 嵌套原生嵌套语法
accent-color表单控件颜色

十七、浏览器兼容性

厂商前缀

/* 部分较新属性可能需要前缀 */
.box {
-webkit-backdrop-filter: blur(10px); /* Safari */
backdrop-filter: blur(10px); /* 标准 */
}
建议

现代开发中,推荐使用 Autoprefixer(PostCSS 插件)自动添加前缀,而不是手动书写。大多数 CSS3 属性在现代浏览器中已经不再需要前缀。

@supports 特性检测

/* 仅在浏览器支持 Grid 时使用 */
@supports (display: grid) {
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
}

/* 不支持时的回退方案 */
@supports not (display: grid) {
.container {
display: flex;
flex-wrap: wrap;
}
}

/* 组合条件 */
@supports (display: grid) and (gap: 16px) {
.container {
display: grid;
gap: 16px;
}
}

十八、面试高频问答

Q1:CSS3 有哪些新特性?请列举至少 10 个。

参考答案

CSS3 新特性主要包括:

  1. 选择器增强:属性选择器(^=$=*=)、结构伪类(:nth-child:first-of-type)、伪元素双冒号(::before
  2. 圆角border-radius
  3. 阴影box-shadowtext-shadow
  4. 渐变linear-gradientradial-gradientconic-gradient
  5. 变换transform(translate、rotate、scale、skew)
  6. 过渡transition
  7. 动画@keyframes + animation
  8. 弹性布局display: flex
  9. 网格布局display: grid
  10. 媒体查询@media
  11. 自定义属性:CSS 变量(--var + var()
  12. 滤镜filterbackdrop-filter
  13. 多列布局column-countcolumn-gap
  14. 自定义字体@font-face
  15. 背景增强:多重背景、background-sizebackground-clip

Q2:transition 和 animation 的区别是什么?

参考答案

特性transition(过渡)animation(动画)
触发方式需要触发条件(如 hover、class 变化)可以自动播放
关键帧只有起始和结束两个状态可以定义多个关键帧(@keyframes
循环不支持循环支持无限循环(infinite
暂停不支持暂停可暂停(animation-play-state: paused
复杂度适合简单的状态切换适合复杂的动画序列
方向只能正向播放支持正向、反向、交替播放

简单来说:transition 适合交互反馈(如按钮 hover 变色),animation 适合独立动画(如加载动画、轮播)。


Q3:如何实现一个元素的水平垂直居中?请列举尽可能多的方法。

参考答案

/* 方法 1:Flexbox(推荐) */
.parent {
display: flex;
justify-content: center;
align-items: center;
}

/* 方法 2:Grid */
.parent {
display: grid;
place-items: center;
}

/* 方法 3:绝对定位 + transform */
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

/* 方法 4:绝对定位 + margin: auto */
.child {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
margin: auto;
width: 200px; /* 需要固定宽高 */
height: 100px;
}

/* 方法 5:Grid + margin(子元素自居中) */
.parent { display: grid; }
.child { margin: auto; }

Q4:CSS3 中的 calc() 函数有什么用?可以混合不同单位吗?

参考答案

calc() 可以在 CSS 中进行动态数学计算,最大的优势是可以混合不同单位进行运算

/* 混合 % 和 px */
width: calc(100% - 200px);

/* 混合 vh 和 px */
height: calc(100vh - 60px);

/* 混合 rem 和 vw */
font-size: calc(1rem + 0.5vw);

注意事项:

  • +- 运算符两侧必须有空格(calc(100%-200px) 会报错)
  • */ 不需要但建议加空格
  • 可以嵌套使用 calc(calc(100% - 20px) / 2)
  • 除法中除数不能为 0

Q5:CSS 变量(自定义属性)和 Sass/Less 变量有什么区别?

参考答案

特性CSS 变量Sass/Less 变量
运行时浏览器运行时生效编译时替换为具体值
作用域遵循 CSS 级联和继承遵循编程语言作用域
动态修改可通过 JS 动态修改编译后无法修改
媒体查询可在 @media 中重新赋值不支持
继承子元素可继承父元素的变量无继承概念
浏览器支持需要现代浏览器编译后兼容所有浏览器
调试DevTools 中可直接查看和修改编译后只能看到最终值

最大区别:CSS 变量是运行时的,可以响应用户交互动态变化(如主题切换),而预处理器变量在编译后就固定了。


Q6:请解释 CSS3 的 transform 为什么不会触发回流(reflow)?

参考答案

transform 不会触发回流的原因是它作用在合成层(Compositing Layer) 上:

  1. 使用 transform 的元素会被浏览器提升到独立的合成层
  2. 变换操作由 GPU 直接处理,不经过 CPU 的布局和绘制流程
  3. 元素在文档流中的位置不会改变,不会影响其他元素的布局

这也是为什么推荐使用 transform: translateX() 代替 lefttop 来做动画的原因——性能更好。

/* 不推荐:触发回流 */
.box {
transition: left 0.3s;
}
.box:hover {
left: 100px;
}

/* 推荐:仅触发合成 */
.box {
transition: transform 0.3s;
}
.box:hover {
transform: translateX(100px);
}

Q7:什么是 BFC?CSS3 中如何触发 BFC?

参考答案

BFC(Block Formatting Context,块级格式化上下文)是一个独立的渲染区域,内部元素的布局不会影响外部。

触发 BFC 的方式

  • overflow 值不为 visible(如 overflow: hiddenoverflow: auto
  • display: flexdisplay: grid(CSS3 新增)
  • display: inline-block
  • display: flow-root(CSS3 新增,最干净的方式)
  • position: absoluteposition: fixed
  • float 值不为 none

BFC 的作用

  1. 清除浮动:BFC 可以包含浮动元素
  2. 防止 margin 合并:相邻 BFC 不会发生 margin 塌陷
  3. 防止浮动元素遮盖:BFC 不与浮动元素重叠
/* 推荐使用 display: flow-root 触发 BFC */
.clearfix {
display: flow-root;
}

Q8:CSS3 硬件加速是什么?哪些属性可以触发?

参考答案

CSS3 硬件加速是指浏览器将某些渲染工作交给 GPU 处理,从而提升动画性能。

可以触发硬件加速的属性

  • transform(推荐)
  • opacity
  • filter
  • will-change
/* 主动告知浏览器即将变化,提前优化 */
.animated-element {
will-change: transform, opacity;
}
注意

不要滥用硬件加速。每个合成层都会占用额外的 GPU 内存。大量使用 will-changetransform: translateZ(0) 来"强制硬件加速"反而可能导致性能下降。只在确实需要优化的动画元素上使用。


Q9:如何实现响应式设计?CSS3 提供了哪些工具?

参考答案

CSS3 为响应式设计提供了完整的工具链:

  1. 媒体查询@media):根据设备特性应用不同样式
  2. 弹性布局(Flexbox):一维自适应布局
  3. 网格布局(Grid):二维自适应布局
  4. 视口单位vwvhvminvmax):相对于视口的尺寸
  5. 百分比 + calc():动态计算尺寸
  6. CSS 变量:在不同媒体查询中重新赋值
  7. min()max()clamp():响应式尺寸约束
  8. 容器查询@container):根据容器尺寸调整样式
/* clamp() 实现响应式字体 */
h1 {
font-size: clamp(1.5rem, 4vw, 3rem);
/* 最小 1.5rem, 期望 4vw, 最大 3rem */
}

Q10:::before:before 有什么区别?

参考答案

功能上没有区别,两者都是选择伪元素。区别在于规范层面

  • CSS2 使用单冒号 :before
  • CSS3 使用双冒号 ::before,目的是将伪元素(::before::after)和伪类(:hover:focus)在语法上区分开

实际开发中,由于浏览器对单冒号写法有良好的向后兼容,两种写法都可以使用。但推荐使用双冒号写法,遵循最新规范。