WEB 前端核心 · 大学一年级

掌握 CSS:让网页漂亮起来

从选择器与盒模型开始,到 Flexbox 与 Grid 布局,再到响应式、动画与现代特性。 本教程与本系列前序课程(C → C++ → Java → Python → SQL → JavaScript → HTML)保持一致的节奏与难度梯度。

🟦 25 章正文 📦 2 个综合项目 ❓ 10 道课堂训练 🎨 视觉 + 布局 📱 响应式与动画
选择器 盒模型 排版与颜色 Flex / Grid 响应式 动画 + 项目

学习指南:CSS 是什么、怎么学、学到什么

CSS = Cascading Style Sheets(层叠样式表),负责网页外观:颜色、字体、布局、动画、响应式。HTML 是骨架,CSS 是皮肤。

0.1 学习路径

  1. 基础语法:选择器、声明、属性、值
  2. 盒模型:外边距、内边距、边框、宽高
  3. 排版:字体、颜色、背景、阴影
  4. 布局:正常流、Flexbox、Grid、Position
  5. 响应式:媒体查询、相对单位、移动优先
  6. 动画:transition、transform、animation

0.2 学习建议

衔接:本教程衔接到本系列 JavaScript 与 Vue 教程,用 CSS 设计界面、用 JS/框架驱动交互。

CSS 引入方式 ⭐⭐⭐

1.1 三种引入

方式语法使用
行内<div style="color:red">❌ 不推荐
内部<style>...</style><head>小型 demo
外部<link rel="stylesheet" href="x.css">✅ 真实项目

1.2 推荐结构

HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>CSS 教程</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>...</body>
</html>

1.3 @import(不推荐)

CSS
/* 在 CSS 里再引入另一个 CSS(性能差,一般不用) */
@import url("reset.css");

1.4 基本语法

CSS
h1 {                       /* 选择器 */
    color:         red;       /* 属性: 值; */
    font-size:     32px;
    font-weight:   bold;
}

选择器 ⭐⭐⭐

2.1 基础选择器

CSS
h1          /* 元素 */
.box       /* class */
#title     /* id */
*           /* 所有元素 */

2.2 关系选择器

CSS
ul li            /* 后代(不限层级) */
ul > li          /* 直接子元素 */
h2 + p           /* 紧邻的兄弟 */
h2 ~ p           /* 之后所有兄弟 */

2.3 属性选择器

CSS
[type="text"]          /* 属性等于某值 */
[class~="active"]      /* 包含某词 */
[href^="https"]       /* 以...开始 */
[href$=".pdf"]         /* 以...结束 */
[title*="教育"]      /* 包含子串 */

2.4 伪类

CSS
a:hover             /* 鼠标悬停 */
a:active            /* 点击瞬间 */
a:focus             /* 键盘聚焦 */
input:disabled      /* 禁用状态 */
input:checked       /* 选中状态 */
li:first-child      /* 第一个子元素 */
li:last-child       /* 最后一个 */
li:nth-child(2)     /* 第 n 个 */
li:nth-child(odd)   /* 奇数 */
li:nth-child(even)  /* 偶数 */

2.5 伪元素

CSS
p::first-line     /* 首行 */
p::first-letter   /* 首字母 */
::before          /* 内容之前 */
::after           /* 内容之后(常用于清除浮动、装饰) */
::placeholder     /* 占位文本 */
::selection       /* 文字被选中时 */

2.6 组合与分组

CSS
h1, h2, h3 {           /* 并列选择器 */
    color: #333;
}

article h2.title {     /* 复合选择器 */
    font-weight: bold;
}

优先级与继承 ⭐⭐

3.1 优先级(特异性)

选择器优先级
行内 style=""1000
#id100
.class / 伪类 / 属性10
元素 / 伪元素1
* / 继承0
⚠️ !important

除非第三方样式冲突,否则别用。会让以后维护非常痛苦。

3.2 继承

文字相关属性默认继承:colorfont-*text-alignline-height
布局属性不继承:widthheightmarginpaddingborder

CSS
body {
    color: #333;
    font-family: "PingFang SC", sans-serif;
}
h1 { color: #000; }   /* 覆盖 */

盒模型 ⭐⭐⭐

CSS 把每个元素都视为一个盒子,由内容、内边距、边框、外边距组成。
margin (外边距) border (边框) padding (内边距) content (内容) 盒模型:margin + border + padding + content

4.1 box-sizing

width 包含box 实际宽
content-box(默认)仅内容width + 2·(padding+border)
border-box(推荐)内容+内边距+边框width
CSS
* {
    box-sizing: border-box;   /* 全局推荐 */
}

.box {
    width:  300px;
    height: 200px;
    padding: 20px;
    border:  5px solid #2965F1;
    margin:  30px;
}

文字与排版 ⭐⭐⭐

5.1 字体

CSS
body {
    font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
    font-size:   16px;
    font-weight: 400;        /* 100-900 或 bold */
    line-height: 1.6;          /* 推荐用单位less,乘数 */
    letter-spacing: 0.5px;
    text-align:  justify;     /* justify 两端对齐 */
}

5.2 加载自定义字体

CSS
@font-face {
    font-family: "MyFont";
    src: url("myfont.woff2") format("woff2");
    font-display: swap;   /* 不阻塞渲染 */
}

颜色与背景 ⭐⭐

6.1 颜色写法

CSS
color: red;                    /* 关键字 */
color: #ff0000;               /* 16进制 */
color: #f00;                  /* 短 16 进制 */
color: rgb(255, 0, 0);
color: rgba(255, 0, 0, 0.5); /* a = 透明度 */
color: hsl(0, 100%, 50%);

6.2 背景

CSS
.card {
    background-color: #fff;
    background-image:    linear-gradient(45deg, #2965F1, #8e44ad);
    background-repeat:   no-repeat;
    background-position: center;
    background-size:     cover;       /* contain 也常用 */
    background-attachment: fixed;    /* 视差 */
}

/* 简写 */
background: #fff url("bg.jpg") no-repeat center / cover;

边框与圆角 ⭐⭐

CSS
.box {
    border: 2px solid #2965F1;          /* width style color */
    border-top: 4px dashed red;

    border-radius: 8px;               /* 全部四个角 */
    border-radius: 50%;                  /* 圆形 */
    border-radius: 12px 4px 20px 0;  /* 左上 右上 右下 左下 */
}

.pill {
    padding: 8px 20px;
    border-radius: 9999px;            /* 胶囊形 */
}

阴影 ⭐⭐

CSS
.card {
    box-shadow: 2px 4px 12px rgba(0,0,0,.1);
    /* x-offset y-offset blur spread color */
}

.glow {
    box-shadow: 0 0 20px #2965F1;
}

h1 {
    text-shadow: 2px 2px 4px rgba(0,0,0,.5);
}

display 属性 ⭐⭐⭐

行为
block块级,独占一行,可设宽高
inline行内,不能设宽高
inline-block行内但能设宽高
none隐藏(不占据位置)
flexFlex 容器
gridGrid 容器
contents自身消失、子元素直接参与父级布局
CSS
.inline-block {
    display: inline-block;
    width:  120px;
    height: 60px;
}

.hide {
    display: none;       /* 隐藏 */
}

.gone {
    visibility: hidden;  /* 隐藏但占位 */
}

Position 定位 ⭐⭐⭐

说明参照
static(默认)正常流
relative相对自身偏移,仍占位自身原位置
absolute脱离文档流最近的 positioned 祖先
fixed相对视口浏览器视口
sticky滚动到阈值后"粘住"滚动容器
CSS
.parent { position: relative; }   /* 子 absolute 参照这个 */

.modal {
    position: fixed;
    top:  50%;
    left: 50%;
    transform: translate(-50%, -50%);   /* 居中 */
}

.head {
    position: sticky;
    top: 0;                          /* 滚动时粘顶部 */
}

Flexbox 弹性布局 ⭐⭐⭐

Flexbox = 一维布局。让一行或一列的元素自动占满空间、对齐、均分。

11.1 基本结构

A
B
C
CSS
.container {
    display: flex;             /* 开启 Flexbox */
    flex-direction: row;    /* row | column | row-reverse | column-reverse */
    justify-content: space-between;  /* 主轴对齐 */
    align-items: center;     /* 交叉轴对齐 */
    flex-wrap: wrap;          /* 自动换行 */
    gap: 10px;                 /* flex 子项间距 */
}

.item {
    flex: 1;                 /* 子项均分剩余空间 */
    flex-basis: 200px;       /* 初始尺寸 */
    flex-grow:   1;          /* 增长比例 */
    flex-shrink: 1;          /* 收缩比例 */
}

11.2 justify-content 速查

效果
flex-start左对齐
flex-end右对齐
center居中
space-between两端贴边,中间均分
space-around两端各留一半间距
space-evenly所有间距相等

11.3 经典:水平垂直居中

CSS
.center {
    display: flex;
    justify-content: center;
    align-items:     center;
    min-height: 100vh;       /* 屏幕高度 */
}

Grid 网格布局 ⭐⭐⭐

Grid = 二维布局。适合网格卡片、仪表盘、整体页面布局。

12.1 三种定义方式

CSS
.grid {
    display: grid;

    /* 方法 1:固定列 */
    grid-template-columns: 200px 200px 200px;

    /* 方法 2:分数单位(推荐) */
    grid-template-columns: 1fr 2fr 1fr;

    /* 方法 3:自适应最小值 */
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));

    grid-template-rows: 100px auto 1fr;

    gap: 16px;
}

.item-wide {
    grid-column: 1 / 3;       /* 跨第 1 到 第 2 列(语法:start / end) */
    grid-row:    1 / span 2;   /* 跨 2 行 */
}

12.2 命名区(更直观)

CSS
.layout {
    display: grid;
    grid-template-areas:
        "header header header"
        "nav    main   aside"
        "footer footer footer";
    grid-template-columns: 200px 1fr 200px;
    grid-template-rows: auto 1fr auto;
}

.layout > header  { grid-area: header; }
.layout > nav    { grid-area: nav; }
.layout > main   { grid-area: main; }
.layout > aside  { grid-area: aside; }
.layout > footer { grid-area: footer; }

float 浮动(了解即可)

历史方案,现代布局请用 Flex / Grid。这里介绍是因为老代码可能看到。

CSS
.img  { float: left; }
.img2 { float: right; }

/* 清除浮动 */
.clear::after {
    content: "";
    display: table;
    clear: both;
}

响应式设计:媒体查询 ⭐⭐⭐

14.1 基本语法

CSS
/* 默认(手机) */
.container { width: 100%; }

/* 平板 ≥768px */
@media (min-width: 768px) {
    .container { width: 750px; }
}

/* 桌面 ≥992px */
@media (min-width: 992px) {
    .container { width: 970px; }
}

/* 大屏 ≥1200px */
@media (min-width: 1200px) {
    .container { width: 1170px; }
}

14.2 媒体查询操作符

类型例子
屏幕宽度(min-width: 768px) / (max-width: 991px)
方向(orientation: landscape | portrait)
是否触屏(hover: hover) / (pointer: fine | coarse)
暗色模式(prefers-color-scheme: dark)
动效偏好(prefers-reduced-motion: reduce)

单位与移动优先 ⭐⭐

15.1 常用单位

单位基于用途
px绝对边框、阴影
%父元素宽度
em父元素 font-size缩放
rem根 html font-size全局缩放
vw / vh视口宽 / 高 1%大块尺寸
vmin / vmax视口较短的边横竖屏
fr剩余空间Grid
clamp()范围限定clamp(min, ideal, max)
CSS
html { font-size: 16px; }   /* 1rem = 16px */

h1 { font-size: clamp(1.5rem, 5vw, 3rem); }
.box { width: min(90%, 1200px); }

/* 卡片响应式 */
.card {
    padding: clamp(12px, 3vw, 24px);
}

过渡 transition ⭐⭐⭐

CSS
.btn {
    background: #2965F1;
    color: white;
    transition: background 0.3s ease,
                transform 0.2s;
}

.btn:hover {
    background: #1e4eba;
    transform: translateY(-2px);
}

.btn:active {
    transform: translateY(0);
}

16.1 缓动函数

特点
ease(默认)慢-快-慢
linear匀速
ease-in加速
ease-out减速
ease-in-out先加速再减速
cubic-bezier(.4,0,.2,1)Material 风格

变换 transform ⭐⭐⭐

CSS
.box {
    /* 平移 */
    transform: translate(20px, -10px);

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

    /* 缩放 */
    transform: scale(1.2);

    /* 倾斜 */
    transform: skew(10deg, 0);

    /* 组合 */
    transform: translateX(50%) rotate(45deg) scale(1.1);
}

/* 3D */
.card3d {
    transform-style: preserve-3d;
    perspective: 1000px;
    transform: rotateY(180deg);
}
提示:transformposition 不同,不影响布局,适合做悬浮交互。

动画 animation ⭐⭐⭐

18.1 @keyframes 与 animation

CSS
@keyframes spin {
    from { transform: rotate(0); }
    to   { transform: rotate(360deg); }
}

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

/* 多个动画 */
.pulse {
    animation: pulse 2s ease-in-out infinite,
               glow  3s ease-in-out alternate infinite;
}

18.2 animation 简写 8 个属性

属性作用
animation-name@keyframes 名
animation-duration持续时间
animation-timing-function缓动
animation-delay延迟
animation-iteration-count次数(infinite 无限)
animation-directionnormal/alternate/reverse
animation-fill-modeforwards/backwards/both
animation-play-staterunning/paused

CSS 变量(Custom Properties)⭐⭐

CSS
:root {
    --color-primary: #2965F1;
    --color-bg:      #fff;
    --radius:        8px;
    --space:         clamp(12px, 3vw, 24px);
}

.btn {
    background: var(--color-primary);
    border-radius: var(--radius);
}

/* 暗色模式 */
[data-theme="dark"] {
    --color-bg:      #1a1f2c;
    --color-primary: #5dade2;
}

.card {
    background: var(--color-bg, white);   /* 可设默认值 */
}

现代 CSS 特性 ⭐⭐

20.1 filter 滤镜

CSS
img {
    filter: blur(5px)          /* 模糊 */
           grayscale(50%)    /* 灰度 */
           brightness(1.2)    /* 变亮 */
           sepia(80%);       /* 复古褐 */
}

.glass {
    backdrop-filter: blur(10px) saturate(1.5);   /* 毛玻璃 */
    background: rgba(255,255,255,0.5);
}

20.2 clip-path 裁剪

CSS
.polygon    { clip-path: polygon(50% 0, 100% 100%, 0 100%); }
.circle     { clip-path: circle(50% at 50% 50%); }
.parallelogram { clip-path: polygon(10% 0, 100% 0, 90% 100%, 0 100%); }

20.3 object-fit

CSS
img {
    width: 100%; height: 200px;
    object-fit: cover;   /* 与 background-size 类似 */
    object-position: center;
}

表单与交互样式 ⭐⭐

21.1 自定义 input

CSS
input[type="text"] {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #d2deec;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.2s;
}

input[type="text"]:focus {
    outline: none;
    border-color: #2965F1;
    box-shadow: 0 0 0 3px rgba(41,101,241,.15);
}

21.2 卡片悬停

CSS
.card {
    padding: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,.06);
    transition: transform 0.3s, box-shadow 0.3s;
}

.card:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 24px rgba(0,0,0,.12);
}

CSS 方法论 BEM ⭐

BEM = Block / Element / Modifier,是流行的 CSS 类名命名规范。

HTML
<article class="card">
    <img     class="card__img" src="x.jpg">
    <h3      class="card__title">标题</h3>
    <p       class="card__desc">描述</p>
    <button  class="card__btn card__btn--primary">行动</button>
</article>
CSS
.card              { /* block */ }
.card__img        { /* element */ }
.card__btn        { /* element */ }
.card__btn--primary{ /* modifier */ }

其他方法论:OOCSSSMACSSUtility-first(Tailwind)也可了解。

项目一:响应式作品集 ⭐⭐⭐

项目 1:响应式作品集页面
难度:⭐⭐⭐Grid + 响应式 + hover

完整 CSS

CSS
@import url("https://fonts.googleapis.com/css?family=Inter:wght@400;700");

:root {
    --primary: #2965F1;
    --bg: #f6f9ff;
    --shadow: 0 2px 8px rgba(0,0,0,.06);
}

* { box-sizing: border-box; }

body {
    margin: 0;
    font-family: Inter, sans-serif;
    background: var(--bg);
}

.container {
    max-width: 1100px;
    margin: 0 auto;
    padding: clamp(16px, 4vw, 40px);
}

.hero {
    text-align: center;
    padding: 80px 20px;
    background: linear-gradient(135deg, #2965F1, #8e44ad);
    color: white;
}
.hero h1 { font-size: clamp(2rem, 6vw, 4rem); margin-bottom: 10px; }

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 24px;
    margin-top: 50px;
}

.card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: var(--shadow);
    transition: transform 0.3s, box-shadow 0.3s;
}
.card:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 24px rgba(0,0,0,.15);
}
.card img { width: 100%; height: 200px; object-fit: cover; }
.card-body { padding: 20px; }

.btn {
    display: inline-block;
    padding: 10px 20px;
    background: var(--primary);
    color: white;
    border-radius: 8px;
    text-decoration: none;
    transition: background 0.2s;
}
.btn:hover { background: #1e4eba; }

对应 HTML

HTML
<section class="hero">
    <h1>我的作品集</h1>
    <p>学生作品 · 课程项目 · 实验记录</p>
</section>
<div class="container">
    <div class="grid">
        <article class="card">
            <img src="p1.jpg" alt="作品 1">
            <div class="card-body">
                <h3>项目一:计算器</h3>
                <p>用 HTML/CSS/JS 实现。</p>
                <a href="#" class="btn">查看</a>
            </div>
        </article>
        …更多卡片…
    </div>
</div>

项目二:交互动效卡片 ⭐⭐⭐

项目 2:3D 翻转 + 加载动画
难度:⭐⭐⭐综合:transform / animation / Flex

3D 翻转卡片

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

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

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

.flip-front, .flip-back {
    position: absolute;
    inset: 0;
    backface-visibility: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
}

.flip-front { background: #2965F1; color: white; }
.flip-back  { background: #8e44ad; color: white; transform: rotateY(180deg); }

Loading 加载动画

CSS
@keyframes bounce {
    0%, 80%, 100% { transform: scale(0); }
    40%            { transform: scale(1); }
}

.loader {
    display: flex;
    gap: 8px;
}
.loader > div {
    width: 16px; height: 16px;
    background: #2965F1;
    border-radius: 50%;
    animation: bounce 1.4s ease-in-out infinite;
}
.loader > div:nth-child(2) { animation-delay: 0.16s; }
.loader > div:nth-child(3) { animation-delay: 0.32s; }

CSS 速查手册 + 课堂训练

25.1 CSS 属性速查

文字 / 字体

  • font-family
  • font-size / weight / style
  • line-height
  • letter-spacing
  • text-align / indent
  • color

盒模型

  • width / height
  • padding / margin
  • border
  • border-radius
  • box-sizing
  • box-shadow

背景

  • background-color
  • background-image
  • background-repeat
  • background-position
  • background-size: cover

布局

  • display (block, flex, grid)
  • position
  • top / left / right / bottom
  • flex-direction / wrap
  • justify-content / align-items
  • grid-template-columns

变换 & 动画

  • transform
  • transition
  • animation / @keyframes
  • will-change

响应式

  • @media (max/min-width)
  • vw / vh / vmin / vmax
  • rem / em
  • clamp(min, ideal, max)

现代

  • filter / backdrop-filter
  • clip-path
  • object-fit
  • aspect-ratio
  • --variable (变量)

交互

  • :hover / focus / active
  • cursor
  • pointer-events
  • scroll-behavior: smooth

25.2 课堂训练(10 题)

Q1. 想让两个并排子元素等分父容器宽度,最适合的方式?
  1. A. table + table-cell
  2. B. flex + flex:1
  3. C. float: left
  4. D. position: absolute
答案:B。Flex 是当代主流方案;float 已过时,absolute 不参与父高度。
Q2. width: 200px; padding: 20px; border: 5px; box-sizing: border-box; 最终元素总宽度?
  1. A. 250px
  2. B. 230px
  3. C. 200px
  4. D. 220px
答案:C。box-sizing: border-box 时 width 包含 padding+border。
Q3. 关于 position: absolute 描述,正确的是?
  1. A. 相对视口定位
  2. B. 相对 body 定位
  3. C. 占原位置
  4. D. 相对最近的 positioned 祖先
答案:D。absolute 相对最近的 position 非 static 祖先,自身不占位。
Q4. 水平垂直居中一个元素,写法?
  1. A. margin: center
  2. B. parent { display: flex; justify-content: center; align-items: center }
  3. C. text-align: center
  4. D. position: center
答案:B。Flex 一行搞定,是现代首选。
Q5. Grid 中 grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)) 的含义?
  1. A. 强制 3 列
  2. B. 列宽固定 200px
  3. C. 自适应列数,每列最小 200px、均分剩余空间
  4. D. 单列布局
答案:C。auto-fill + minmax 是经典响应式网格写法。
Q6. @media (prefers-color-scheme: dark) 用于?
  1. A. 暗色模式
  2. B. 减少动效
  3. C. 横屏
  4. D. 触屏
答案:A。prefers-color-scheme 切换深浅色,主流 OS 已支持。
Q7. 想做动画"鼠标悬停时用 transition 平滑过渡",哪个写法正确?
  1. A. 写 @keyframes 然后 animation
  2. B. 写 transform: hover
  3. C. 在 :hover 内加 transition
  4. D. 在基类加 transition 属性,:hover 修改属性值
答案:D。transition 加在「原始状态」而非 hover;hover 只改值。
Q8. --primary: #2965F1; 这种写法是?
  1. A. SCSS 变量
  2. B. CSS Custom Property(CSS 变量)
  3. C. Less 变量
  4. D. JS 变量
答案:B。原生 CSS 变量,用 var(--primary) 引用。
Q9. 让图片填充容器且不拉伸,用?
  1. A. width: 100%
  2. B. background-size: cover
  3. C. object-fit: cover
  4. D. 强制设置高度
答案:C。<img> 用 object-fit;CSS 背景图用 background-size。
Q10. 想让页面在手机、平板、PC 都能看,应该?
  1. A. 媒体查询 + 相对单位(rem/%/vw)+ Flex/Grid
  2. B. 写 3 个 HTML 文件
  3. C. 用 JS 检测设备
  4. D. 缩小一切
答案:A。响应式设计的三大要素。

写在最后:CSS 是 Web 的画笔

🎓 与本系列衔接
HTML     → 骨架(语义、文档、表单)
CSS      → 皮肤(颜色、布局、响应式、动画)
JavaScript→ 行为(DOM、事件、异步)
Vue      → 框架(组件化、响应式数据)

掌握 CSS 后,再学 Vue 会发现:组件 scoped 样式和动态 class 绑定会非常重要。

练习建议:把博客、官网、个人主页的样式全部用纯 CSS 重写一遍练手。