CSS3 教程

CSS3 教程

CSS3 是 CSS 的最新版本,在 CSS2 基础上增加了圆角、渐变、阴影、动画、弹性布局等大量新特性,是现代 Web 设计的基石。

本教程包含

  • 视觉篇:边框、背景、渐变、文本效果、字体
  • 动效篇:2D/3D 转换、过渡、动画
  • 布局篇:多列、用户界面、弹性盒子(Flex)、多媒体查询、网格布局
  • 应用篇:图片、按钮、分页、框大小

CSS3 新特性一览

选择器: 属性选择器、伪类(:nth-child)
视觉效果: border-radius、box-shadow、gradient
动效: transform、transition、@keyframes 动画
布局: flexbox、grid、多列
响应式: @media 查询
文本: text-shadow、word-wrap、文字描边

浏览器支持

现代浏览器全面支持 CSS3,部分老特性需加前缀(-webkit-、-moz-)。

CSS3 简介

CSS3 简介

CSS3 不是单一规范,而是被拆分成多个独立模块,各模块单独演进。

模块化结构

选择器模块
背景与边框模块
文本装饰模块
2D/3D 转换模块
过渡与动画模块
多列布局模块
弹性盒(Flex)模块
网格(Grid)模块
UI 模块

CSS3 优势

  • 减少图片依赖(圆角、渐变、阴影用代码实现)
  • 更丰富的动画(替代 Flash/JS 动画)
  • 灵活布局(Flex/Grid 告别浮动布局)
  • 更好的性能与维护性

基础示例

.card {
  border-radius: 12px;        /* 圆角(以前要切图) */
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);  /* 阴影 */
  background: linear-gradient(135deg, #667eea, #764ba2);  /* 渐变 */
  transition: all 0.3s ease;  /* 过渡 */
}

.card:hover {
  transform: translateY(-4px);  /* 悬浮上移 */
}

浏览器前缀

-webkit-   Chrome/Safari/Edge
-moz-      Firefox
-ms-       旧版 IE/Edge
-o-        旧版 Opera

/* 现代浏览器大多无需前缀 */
border-radius: 10px;

CSS3 边框

CSS3 边框

CSS3 为边框新增圆角、图片边框等特性。

圆角 border-radius

.rounded {
  border-radius: 10px;          /* 四角统一 */
}

.different {
  border-radius: 10px 20px;     /* 左上右下 10px, 右上左下 20px */
  border-radius: 10px 20px 30px 40px;  /* 顺时针: 左上右上右下左下 */
}

.circle {
  border-radius: 50%;           /* 圆形 */
  width: 100px;
  height: 100px;
}

/* 指定单个角 */
border-top-left-radius: 10px;
border-top-right-radius: 20px;
border-bottom-right-radius: 30px;
border-bottom-left-radius: 40px;

椭圆圆角

/* 水平/垂直半径 */
border-radius: 50px / 20px;   /* 水平50px 垂直20px */

图片边框 border-image

.img-border {
  border: 15px solid transparent;
  border-image: url(border.png) 30 round;
}

/* border-image 属性 */
border-image-source: url(x.png);   /* 图片来源 */
border-image-slice: 30;            /* 切割宽度 */
border-image-width: 15px;          /* 边框宽度 */
border-image-repeat: round;        /* 平铺方式 */

阴影(见后章)与渐变边框

.gradient-border {
  border: 3px solid transparent;
  background: linear-gradient(white, white) padding-box,
              linear-gradient(45deg, red, blue) border-box;
}

CSS3 背景

CSS3 背景

CSS3 扩展了背景功能:多背景、背景尺寸、背景原点等。

多背景

.multi-bg {
  background:
    url(flower.png) no-repeat right bottom,
    url(paper.png) no-repeat left top,
    #f0f0f0;              /* 最后是背景色 */
}

background-size 背景尺寸

.bg-cover {
  background-size: cover;    /* 铺满(裁剪) */
}

.bg-contain {
  background-size: contain;  /* 完整显示(留白) */
}

.bg-custom {
  background-size: 200px 100px;   /* 指定尺寸 */
  background-size: 50% 50%;       /* 百分比 */
}

background-origin 背景原点

background-origin: padding-box;   /* 默认,从内边距开始 */
background-origin: border-box;    /* 从边框开始 */
background-origin: content-box;   /* 从内容开始 */

background-clip 背景裁剪

background-clip: border-box;   /* 默认 */
background-clip: padding-box;
background-clip: content-box;
background-clip: text;         /* 文字裁剪(文字渐变效果) */

文字渐变效果

.gradient-text {
  background: linear-gradient(90deg, red, blue);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;    /* 文字透明露出背景 */
}

简写属性

background: url(bg.png) no-repeat center / cover, #fff;
/* 注意: size 紧跟 position 用 / 分隔 */

CSS3 渐变

CSS3 渐变

渐变(gradient)用代码实现平滑过渡的视觉背景,替代渐变图片。

线性渐变 linear-gradient

/* 默认从上到下 */
background: linear-gradient(red, blue);

/* 指定方向 */
background: linear-gradient(to right, red, blue);
background: linear-gradient(to bottom right, red, blue);
background: linear-gradient(45deg, red, blue);

/* 多色渐变 */
background: linear-gradient(red, yellow, green);

/* 指定颜色位置 */
background: linear-gradient(red 0%, yellow 50%, blue 100%);

/* 透明渐变 */
background: linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.7));

径向渐变 radial-gradient

/* 从中心扩散 */
background: radial-gradient(red, blue);

/* 圆形与椭圆 */
background: radial-gradient(circle, red, blue);
background: radial-gradient(ellipse, red, blue);

/* 指定中心位置 */
background: radial-gradient(circle at top left, red, blue);
background: radial-gradient(circle at 30% 40%, yellow, green);

重复渐变

background: repeating-linear-gradient(45deg, red, blue 10px);
background: repeating-radial-gradient(circle, red, blue 20px);

常用渐变示例

/* 按钮渐变 */
.btn {
  background: linear-gradient(to right, #4facfe, #00f2fe);
}

/* 背景叠加渐变遮罩 */
.hero {
  background:
    linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
    url(hero.jpg) center/cover;
}

渐变在线工具

cssgradient.io / uiGradients.com(配色方案)

CSS3 文本效果

CSS3 文本效果

CSS3 为文本提供阴影、描边、溢出处理等效果。

text-shadow 文字阴影

/* 水平偏移 垂直偏移 模糊 颜色 */
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);

/* 多层阴影 */
text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;

/* 浮雕效果 */
text-shadow: 1px 1px 1px #fff, -1px -1px 1px #333;

文字描边 -webkit-text-stroke

.outline-text {
  -webkit-text-stroke: 2px blue;         /* 宽度 颜色 */
  -webkit-text-stroke-width: 2px;
  -webkit-text-stroke-color: red;
  color: white;   /* 空心字效果 */

文本溢出处理

.ellipsis {
  white-space: nowrap;          /* 不换行 */
  overflow: hidden;             /* 隐藏溢出 */
  text-overflow: ellipsis;      /* 省略号 */
}

/* 多行省略 */
.multi-line {
  display: -webkit-box;
  -webkit-line-clamp: 2;        /* 显示2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

换行与断词

word-wrap: break-word;        /* 长单词换行 */
word-break: break-all;        /* 任意断行 */
overflow-wrap: anywhere;      /* 任意位置换行 */

其他文本属性

text-align-last: center;      /* 末行对齐 */
text-justify: inter-word;     /* 两端对齐方式 */
writing-mode: vertical-rl;    /* 竖排文字 */

CSS3 字体

CSS3 字体

CSS3 通过 @font-face 使用自定义字体,无需依赖用户系统字体。

@font-face 用法

@font-face {
  font-family: "MyFont";
  src: url("myfont.woff2") format("woff2"),
       url("myfont.woff") format("woff");
  font-weight: normal;
  font-style: normal;
}

.my-text {
  font-family: "MyFont", sans-serif;
}

字体格式

WOFF2   最新,压缩率最高(推荐)
WOFF    兼容性好
TTF/OTF 通用格式
EOT     仅旧版 IE

Google Fonts(免费字体)

<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC&display=swap" rel="stylesheet">

/* CSS 使用 */
body {
  font-family: "Noto Sans SC", sans-serif;
}

字体描述属性

@font-face {
  font-family: "MyFont";
  src: url("bold.woff2") format("woff2");
  font-weight: bold;        /* 该文件对应粗体 */
}

/* 使用时自动选择对应文件 */
.bold-text {
  font-family: "MyFont", sans-serif;
  font-weight: bold;
}

字体加载策略

font-display: swap;      /* 先用系统字体,加载完替换(推荐) */
font-display: block;     /* 隐藏文字直到加载 */
font-display: fallback;  /* 短时间等待 */
font-display: optional;  /* 快速失败 */

图标字体

Font Awesome / Material Icons
<i class="fa fa-home"></i>

CSS3 2D 转换

CSS3 2D 转换

transform 属性对元素进行移动、旋转、缩放、倾斜等 2D 变换。

基本转换函数

.translate {
  transform: translate(50px, 20px);    /* 平移 */
  transform: translateX(50px);         /* 水平平移 */
  transform: translateY(20px);         /* 垂直平移 */
}

.rotate {
  transform: rotate(45deg);            /* 旋转 */
}

.scale {
  transform: scale(1.5);               /* 缩放(1.5倍) */
  transform: scaleX(2);                /* 水平缩放 */
  transform: scaleY(0.5);              /* 垂直缩放 */
}

.skew {
  transform: skew(20deg);              /* 倾斜 */
  transform: skewX(30deg);
  transform: skewY(20deg);
}

组合使用

.combined {
  transform: translate(50px, 50px) rotate(45deg) scale(1.2);
}

变换原点 transform-origin

.origin {
  transform-origin: left top;      /* 左上角 */
  transform-origin: 0% 0%;
  transform-origin: 50% 50%;       /* 默认: 中心 */
  transform: rotate(45deg);
}

matrix(矩阵)

/* 六个值: scaleX skewY skewX scaleY translateX translateY */
transform: matrix(1, 0, 0, 1, 50, 20);   /* 等价 translate(50,20) */

实际应用

/* 元素居中(经典技巧) */
.center {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

/* 悬浮效果 */
.card:hover {
  transform: scale(1.05);
  transition: transform 0.3s;
}

CSS3 3D 转换

CSS3 3D 转换

CSS3 支持 3D 空间内的元素变换,实现立体效果。

3D 变换函数

.rotateX {
  transform: rotateX(45deg);     /* 绕X轴旋转(上下) */
}

.rotateY {
  transform: rotateY(45deg);     /* 绕Y轴旋转(左右) */
}

.rotateZ {
  transform: rotateZ(45deg);     /* 绕Z轴旋转(平面) */
}

.translate3d {
  transform: translate3d(10px, 20px, 30px);   /* 3D平移 */
  transform: translateZ(50px);                /* Z轴平移 */
}

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

透视 perspective

/* 在父元素设置透视(产生近大远小) */
.scene {
  perspective: 800px;    /* 视距,越小效果越强 */
}

/* 子元素 3D 变换 */
.scene .child {
  transform: rotateY(45deg);
}

perspective() 函数

.child {
  transform: perspective(800px) rotateY(45deg);
}

transform-style 与 backface-visibility

.scene {
  transform-style: preserve-3d;   /* 保留3D(默认flat) */
}

.card {
  backface-visibility: hidden;    /* 背面隐藏 */
}

/* 翻牌效果 */
.flip-card-inner {
  transform-style: preserve-3d;
  transition: transform 0.8s;
}
.flip-card:hover .flip-card-inner {
  transform: rotateY(180deg);
}

注意

3D 效果依赖 GPU,性能较好
父元素 overflow:hidden 可能破坏 3D 效果

CSS3 过渡

CSS3 过渡

过渡(transition)让属性变化平滑过渡,是交互效果的基石。

基本用法

.box {
  width: 100px;
  height: 100px;
  background: blue;
  transition: width 1s, height 1s, background 1s;   /* 指定属性 */
}

.box:hover {
  width: 200px;
  height: 200px;
  background: red;      /* 平滑过渡而非突变 */
}

过渡属性

transition-property: width;          /* 属性(可逗号多值) */
transition-duration: 1s;             /* 时长 */
transition-timing-function: ease;    /* 缓动 */
transition-delay: 0.5s;              /* 延迟 */

/* 简写 */
transition: property duration timing-function delay;
transition: all 0.3s ease 0s;        /* 全部属性 */

缓动函数

ease          慢快慢(默认)
linear        匀速
ease-in       慢到快
ease-out      快到慢
ease-in-out   慢快慢(比ease更对称)
cubic-bezier(0.1, 0.7, 1.0, 0.1)   自定义
steps(5)      步进(打字机效果)

常用交互过渡

.btn {
  transition: background 0.3s, transform 0.3s;
}
.btn:hover {
  background: darkblue;
  transform: translateY(-2px);
}

/* 卡片悬停 */
.card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.15);
}

注意

display:none 无法过渡(用 opacity+visibility)
过渡需要初始值和结束值(数字/颜色等可插值属性)

CSS3 动画

CSS3 动画

@keyframes 定义关键帧动画,可循环、暂停、控制播放。

定义动画

@keyframes bounce {
  0%   { transform: translateY(0); }
  50%  { transform: translateY(-30px); }
  100% { transform: translateY(0); }
}

/* 使用 */
.ball {
  animation: bounce 1s ease infinite;   /* 无限循环 */
}

动画属性

animation-name: bounce;           /* 名称 */
animation-duration: 2s;           /* 时长 */
animation-timing-function: ease;  /* 缓动 */
animation-delay: 0.5s;            /* 延迟 */
animation-iteration-count: 3;     /* 次数(infinite无限) */
animation-direction: alternate;   /* 方向: 正放/倒放 */
animation-fill-mode: forwards;    /* 结束后保持最后一帧 */
animation-play-state: paused;     /* 暂停/运行 */

/* 简写 */
animation: name duration timing delay count direction fill-mode;

动画方向

normal        默认,正向
reverse       反向
alternate     正反交替
alternate-reverse  反-正交替

多关键帧与百分比

@keyframes rainbow {
  0%   { background: red; }
  25%  { background: yellow; }
  50%  { background: green; }
  75%  { background: blue; }
  100% { background: purple; }
}

实际应用

/* 加载动画 */
.spinner {
  width: 40px; height: 40px;
  border: 4px solid #ddd;
  border-top-color: blue;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 文字淡入 */
.fade-in {
  animation: fade 1.5s ease-in;
}
@keyframes fade {
  from { opacity: 0; }
  to   { opacity: 1; }
}

过渡 vs 动画

过渡: 需要触发(hover等),一次到位
动画: 自动执行,多关键帧,可循环控制

CSS3 多列

CSS3 多列

多列布局让文本像报纸一样分列显示。

基本属性

.multi-col {
  column-count: 3;           /* 3列 */
  column-gap: 40px;          /* 列间距 */
  column-rule: 1px solid #ccc;  /* 列间分隔线 */
}

列宽与列数

.col-width {
  column-width: 200px;       /* 每列最小宽度,自动分列 */
}

/* 两者都用时: 取先满足的条件 */
.auto-col {
  columns: 200px 3;          /* 简写: 宽度 数量 */
}

跨列与列内分页

h2 {
  column-span: all;          /* 标题跨所有列 */
}

/* 避免元素被分列截断 */
.item {
  break-inside: avoid;       /* 防止分列截断 */
  /* 旧写法: -webkit-column-break-inside: avoid */
}

简写

columns: 3 200px;            /* count width */
column-gap: 40px;
column-rule: 2px dashed blue;

应用场景

杂志式排版
长文本阅读优化
卡片瀑布流(配合 break-inside)

注意

多列主要用于文本排版
响应式下配合 @media 调整列数

CSS3 用户界面

CSS3 用户界面

CSS3 提供调整尺寸、轮廓、框大小等 UI 相关属性。

resize 调整尺寸

textarea {
  resize: both;       /* 可拖拽调整 */
  resize: horizontal; /* 仅水平 */
  resize: vertical;   /* 仅垂直 */
  resize: none;       /* 禁止(默认 textarea 可调) */
}

outline 轮廓

.focus-box:focus {
  outline: 3px solid blue;         /* 聚焦描边 */
  outline-offset: 2px;             /* 偏移(外扩/内缩) */
}

/* 去除默认轮廓(需配合自定义焦点样式) */
button:focus {
  outline: none;
}

box-sizing 框大小

.border-box {
  box-sizing: border-box;   /* 宽高包含 padding 和 border */
}

.content-box {
  box-sizing: content-box;  /* 默认: 宽高只含内容 */
}

/* 全局推荐 */
* {
  box-sizing: border-box;
}

appearance 外观

select, input {
  appearance: none;         /* 移除默认外观 */
  -webkit-appearance: none;
}

/* 自定义下拉箭头 */
select {
  background: url(arrow.svg) no-repeat right center;
}

其他 UI 属性

cursor: pointer;           /* 鼠标样式 */
user-select: none;         /* 禁止选中 */
pointer-events: none;      /* 禁用事件 */
caret-color: red;          /* 光标颜色 */
scroll-behavior: smooth;   /* 平滑滚动 */

CSS3 图片

CSS3 图片

用 CSS3 为图片添加圆角、滤镜、响应式等效果。

圆角与形状

img {
  border-radius: 50%;       /* 圆形头像 */
}

.rounded-img {
  border-radius: 12px;      /* 圆角图片 */
}

响应式图片

img {
  max-width: 100%;      /* 不超过容器 */
  height: auto;         /* 保持比例 */
}

/* 铺满容器并裁剪 */
.cover {
  width: 100%;
  height: 300px;
  object-fit: cover;    /* 裁剪填充 */
}

/* object-fit 值 */
object-fit: fill;       /* 拉伸(变形) */
object-fit: contain;    /* 完整显示 */
object-fit: cover;      /* 覆盖裁剪(推荐) */
object-fit: none;       /* 原始大小 */
object-fit: scale-down; /* 取小者 */

滤镜 filter

img {
  filter: grayscale(100%);    /* 灰度 */
  filter: blur(5px);          /* 模糊 */
  filter: brightness(0.8);    /* 亮度 */
  filter: contrast(150%);     /* 对比度 */
  filter: sepia(100%);        /* 怀旧 */
  filter: saturate(200%);     /* 饱和度 */
  filter: hue-rotate(90deg);  /* 色相旋转 */
}

/* 组合 */
filter: grayscale(50%) blur(2px);

/* 悬停彩色 */
img {
  filter: grayscale(100%);
  transition: filter 0.3s;
}
img:hover {
  filter: grayscale(0);
}

其他图片效果

/* 图片上文字(叠加) */
.img-text {
  position: relative;
  background: url(x.jpg) center/cover;
}
.img-text::after {
  content: "";
  position: absolute; inset: 0;
  background: rgba(0,0,0,0.4);    /* 暗化层 */
}

CSS3 按钮

CSS3 按钮

用 CSS3 打造现代风格按钮:渐变、阴影、悬停、波纹等。

基础样式

.btn {
  padding: 12px 24px;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

渐变按钮

.btn-gradient {
  background: linear-gradient(to right, #4facfe, #00f2fe);
  color: white;
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.4);
}
.btn-gradient:hover {
  box-shadow: 0 6px 20px rgba(79, 172, 254, 0.6);
  transform: translateY(-2px);
}
.btn-gradient:active {
  transform: translateY(0);
}

描边按钮

.btn-outline {
  background: transparent;
  border: 2px solid #4facfe;
  color: #4facfe;
}
.btn-outline:hover {
  background: #4facfe;
  color: white;
}

波纹效果(点击)

.btn-ripple {
  position: relative;
  overflow: hidden;
}
.btn-ripple::after {
  content: "";
  position: absolute;
  width: 100%; height: 100%;
  top: 0; left: 0;
  background: rgba(255,255,255,0.3);
  transform: scale(0);
  border-radius: 50%;
  transition: transform 0.5s;
}
.btn-ripple:active::after {
  transform: scale(3);
  opacity: 0;
}

加载中按钮

.btn-loading {
  color: transparent;      /* 隐藏文字 */
  position: relative;
}
.btn-loading::after {
  content: "";
  position: absolute;
  left: 50%; top: 50%;
  width: 20px; height: 20px;
  margin: -10px 0 0 -10px;
  border: 2px solid white;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

禁用态

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

CSS3 分页

CSS3 分页

分页组件用于列表数据的分页导航,常见于博客、表格。

基础分页

.pagination {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination a {
  padding: 8px 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
  color: #333;
  text-decoration: none;
  transition: all 0.2s;
}

.pagination a:hover {
  background: #f0f0f0;
}

/* 当前页 */
.pagination a.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

圆角分页

.pagination a {
  border-radius: 50%;
  width: 40px; height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

禁用与省略

.pagination a.disabled {
  pointer-events: none;
  opacity: 0.5;
}

.pagination a.ellipsis {
  pointer-events: none;
  border: none;
}

前后翻页

.pagination a.prev,
.pagination a.next {
  font-weight: bold;
}

/* 悬浮效果 */
.pagination a:hover:not(.active):not(.disabled) {
  background: #e9ecef;
  transform: translateY(-2px);
}

完整示例

<div class="pagination">
  <a href="#" class="prev">«</a>
  <a href="#">1</a>
  <a href="#" class="active">2</a>
  <a href="#">3</a>
  <a href="#" class="ellipsis">…</a>
  <a href="#">10</a>
  <a href="#" class="next">»</a>
</div>

CSS3 框大小

CSS3 框大小

box-sizing 决定元素的宽高计算方式,是布局的基础认知。

两种模型

content-box(默认):
  width = 内容宽度
  实际占位 = width + padding + border

border-box:
  width = 内容 + padding + border
  实际占位 = width(固定)

示例对比

.box-a {           /* content-box */
  width: 200px;
  padding: 20px;
  border: 10px solid #ccc;
  /* 实际占位: 200 + 40 + 20 = 260px */
}

.box-b {           /* border-box */
  width: 200px;
  padding: 20px;
  border: 10px solid #ccc;
  /* 实际占位: 200px(内容自动收缩到140px) */
}

全局设置(推荐)

/* 所有元素统一 border-box */
* {
  box-sizing: border-box;
}

/* 或包含伪元素 */
*, *::before, *::after {
  box-sizing: border-box;
}

为什么推荐 border-box

1. 布局计算直观(width 即最终宽度)
2. 百分比宽度+padding 不会溢出
3. 响应式更安全

/* 50% + padding 溢出问题(两列布局) */
.col {
  width: 50%;        /* content-box 时加上 padding 会超出 */
  padding: 20px;
}

经典布局应用

/* 三列等宽 + 间距,不溢出 */
.row {
  display: flex;
  gap: 20px;
}
.col {
  flex: 1;
  padding: 16px;
  /* border-box 保证 flex:1 生效 */
}

CSS3 弹性盒子

CSS3 弹性盒子(Flexbox)

Flexbox 是一维布局模型,彻底改变了传统浮动布局,是现代布局的核心。

容器属性

.container {
  display: flex;              /* 开启弹性布局 */
  flex-direction: row;        /* 主轴方向: row/column */
  flex-wrap: wrap;            /* 换行 */
  justify-content: center;    /* 主轴对齐 */
  align-items: center;        /* 交叉轴对齐 */
  align-content: space-between;  /* 多行对齐 */
  gap: 10px;                  /* 间距 */
}

justify-content(主轴)

flex-start      起点(默认)
flex-end        终点
center          居中
space-between   两端对齐
space-around    每项两侧等距
space-evenly    完全等距

align-items(交叉轴)

stretch        拉伸(默认)
flex-start     起点
flex-end       终点
center         居中
baseline       基线

子项属性

.item {
  flex-grow: 1;        /* 伸展比例 */
  flex-shrink: 0;      /* 收缩(0不缩) */
  flex-basis: 200px;   /* 基础尺寸 */
  align-self: center;  /* 单独对齐 */
  order: 1;            /* 排序 */
}

/* 简写 */
flex: 1;               /* grow 1 shrink 1 basis 0% */
flex: 1 0 200px;

经典布局

/* 垂直水平居中(最常用) */
.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

/* 导航栏 */
.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 圣杯: 左右固定中间自适应 */
.main {
  display: flex;
}
.sidebar { width: 200px; }
.content { flex: 1; }

CSS3 多媒体查询

CSS3 多媒体查询

@media 让 CSS 根据设备特性(屏幕宽度等)应用不同样式,是响应式设计核心。

基本语法

/* 屏幕且最大宽度 600px */
@media screen and (max-width: 600px) {
  body { background: red; }
}

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

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

常用断点

@media (max-width: 480px)  手机
@media (max-width: 768px)  平板
@media (max-width: 1024px) 笔记本
@media (min-width: 1200px) 大屏

/* 推荐: 移动优先用 min-width */
@media (min-width: 768px) { ... }   /* ≥768px 生效 */

逻辑组合

/* 与 */
@media screen and (min-width: 600px) and (max-width: 900px) { }

/* 或(逗号) */
@media (max-width: 600px), (orientation: landscape) { }

/* 非 */
@media not print { }

/* 简化范围语法 */
@media (600px <= width <= 900px) { }   /* 新语法 */

设备特性

width / height      视口宽高
device-width        设备宽
orientation         横竖屏
resolution          分辨率
aspect-ratio        宽高比
prefers-color-scheme 深色模式
prefers-reduced-motion 减少动画偏好
hover               是否支持悬停

响应式示例

.grid {
  display: grid;
  grid-template-columns: 1fr;        /* 移动: 1列 */
}

@media (min-width: 768px) {
  .grid { grid-template-columns: repeat(3, 1fr); }  /* 桌面: 3列 */
}

/* 移动端隐藏导航,显示菜单按钮 */
.menu { display: none; }
@media (min-width: 768px) {
  .menu { display: flex; }
  .menu-btn { display: none; }
}

CSS3 多媒体查询实例

CSS3 多媒体查询实例

通过完整实例演示响应式设计,实现移动端友好的页面。

实例:响应式导航

/* 默认(移动端): 汉堡菜单 */
.nav-links {
  display: none;
  flex-direction: column;
}

.menu-toggle {
  display: block;
}

/* 平板及以上: 横排导航 */
@media (min-width: 768px) {
  .nav-links {
    display: flex;
    flex-direction: row;
    gap: 20px;
  }
  .menu-toggle { display: none; }
}

实例:响应式网格

.cards {
  display: grid;
  gap: 16px;
  grid-template-columns: 1fr;
}

@media (min-width: 600px) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}

@media (min-width: 992px) {
  .cards { grid-template-columns: repeat(4, 1fr); }
}

实例:移动优先文本

body { font-size: 16px; }

@media (min-width: 768px) {
  body { font-size: 18px; }      /* 大屏更大字号 */
}

/* 图片自适应 */
img {
  max-width: 100%;
  height: auto;
}

实例:触屏友好

/* 移动端加大按钮与间距 */
.btn {
  padding: 12px 20px;
}
@media (min-width: 768px) {
  .btn { padding: 8px 16px; }   /* 桌面可小一些 */
}

组合:完整响应式布局

.page {
  display: grid;
  grid-template-areas:
    "header"
    "main"
    "sidebar"
    "footer";
}

@media (min-width: 768px) {
  .page {
    grid-template-areas:
      "header header"
      "main sidebar"
      "footer footer";
    grid-template-columns: 1fr 300px;
  }
}

测试工具

浏览器开发者工具 → 设备模拟器
可调整多种设备宽度实时预览

CSS 网格布局

CSS 网格布局(Grid)

Grid 是二维布局系统,同时控制行和列,是 CSS3 布局的集大成者。

基础概念

.grid {
  display: grid;
  grid-template-columns: 100px 100px 100px;   /* 3列 */
  grid-template-rows: 100px 100px;            /* 2行 */
  gap: 10px;
}

fr 单位(分数)

grid-template-columns: 1fr 2fr 1fr;   /* 1:2:1 */
grid-template-columns: 200px 1fr;     /* 固定+自适应 */
grid-template-columns: repeat(3, 1fr);  /* 重复3次 */

repeat 与 minmax

grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
/* 自动填充,每列至少200px,自动换行 */

grid-template-columns: minmax(100px, 1fr) 200px;

网格线布局

.item {
  grid-column: 1 / 3;      /* 占1-3列 */
  grid-row: 1 / 2;         /* 占第1行 */
  grid-area: 1 / 1 / 3 / 3; /* 上/左/下/右 */
}

/* 简写 span */
grid-column: span 2;       /* 跨2列 */
grid-row: span 2;          /* 跨2行 */

对齐

justify-items: center;     /* 水平(单元格内) */
align-items: center;       /* 垂直(单元格内) */
justify-content: center;   /* 整个网格水平 */
align-content: center;     /* 整个网格垂直 */

Grid vs Flex

Grid: 二维(行+列同时),适合整体页面布局
Flex: 一维(单方向),适合组件内部排列
实际项目两者常组合使用

CSS 网格容器

CSS 网格容器

深入网格容器的关键属性:模板、自动布局、命名区域。

grid-template 系列

/* 列与行模板 */
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto 200px;

/* 简写 */
grid-template: 100px auto / repeat(3, 1fr);
/* 行 / 列 */

命名区域 grid-template-areas

.layout {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  gap: 10px;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

自动放置

/* 自动行大小 */
grid-auto-rows: 100px;
grid-auto-rows: minmax(100px, auto);

/* 自动流方向 */
grid-auto-flow: row;          /* 默认: 行优先 */
grid-auto-flow: column;       /* 列优先 */
grid-auto-flow: dense;        /* 密集填充 */

对齐与间距

gap: 20px;              /* 行列间距 */
column-gap: 30px;       /* 列间距 */
row-gap: 10px;          /* 行间距 */

justify-content: space-between;   /* 网格对齐 */
align-content: center;

隐式网格

/* 超出模板的项自动进入隐式网格 */
.grid {
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 120px;   /* 隐式行高 */
}

完整示例

/* 图片画廊 */
.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  grid-auto-rows: 200px;
  gap: 10px;
}
.gallery img {
  width: 100%; height: 100%;
  object-fit: cover;
}

CSS 网格元素

CSS 网格元素

网格子元素的定位与布局:跨列行、对齐、排序。

跨越单元格

.featured {
  grid-column: span 2;    /* 跨2列 */
  grid-row: span 2;       /* 跨2行 */
}

/* 指定起止线 */
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 1;
grid-row-end: 3;

/* 简写 */
grid-column: 1 / 3;
grid-row: 1 / 3;
grid-area: 1 / 1 / 3 / 3;

单元格内对齐

.item {
  justify-self: center;    /* 水平 */
  align-self: end;         /* 垂直 */
  place-self: center;      /* 简写: 水平 垂直 */
}

/* 值: start / end / center / stretch(默认) */

排序 order

.item {
  order: 1;    /* 数字小的先(默认0) */
}

z-index 层级

.overlap {
  grid-column: 1 / 3;
  grid-row: 1 / 2;
  z-index: 2;     /* 覆盖其他项 */
}

重叠布局

.hero {
  display: grid;
}
.hero img {
  grid-area: 1 / 1;       /* 同位置重叠 */
}
.hero .title {
  grid-area: 1 / 1;       /* 覆盖在图片上 */
  align-self: end;
  padding: 20px;
  color: white;
}

完整卡片网格

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.card {
  display: flex;
  flex-direction: column;
}

.card img { height: 150px; object-fit: cover; }
.card .body { flex: 1; padding: 16px; }

Grid 总结

容器: display:grid + 模板列/行
元素: grid-column/row 定位跨越
对齐: justify/align + self
组合: 与 Flexbox 搭配实现复杂布局
第 1 / 23 节