核心知识点
1. CSS 简介
1.1 什么是 CSS?
CSS (Cascading Style Sheets, 层叠样式表) 是一种用来为结构化文档(如 HTML 或 XML)添加样式(字体、颜色、间距等)的计算机语言。它主要用于定义网页的视觉表现。
1.2 CSS 的作用
- 关注点分离: 将内容结构 (HTML) 与视觉表现 (CSS) 分开,使代码更清晰、易于维护。
- 提高可维护性: 修改样式只需更改 CSS 文件,无需改动 HTML 结构。
- 提升可访问性: 良好的 CSS 可以改善屏幕阅读器等辅助技术的用户体验。
- 一致性: 轻松地为网站的所有页面应用统一的样式。
- 丰富表现力: 实现复杂的布局、动画和视觉效果。
2. CSS 基础语法与引入方式
2.1 基本语法
CSS 规则由两部分组成:选择器 (Selector) 和声明块 (Declaration Block)。声明块包含一条或多条声明,每条声明是一个属性 (Property) 和值 (Value) 对。
/* 选择器 { 属性: 值; 属性: 值; ... } */
h1 {
color: blue; /* 声明 1 */
font-size: 24px; /* 声明 2 */
}
2.2 引入方式
- 外部样式表 (External Stylesheet): 使用
<link>标签链接外部.css文件 (最推荐的方式)。 - 内部样式表 (Internal Stylesheet): 在 HTML
<head>部分使用<style>标签定义 CSS。 - 内联样式 (Inline Styles): 直接在 HTML 元素的
style属性中定义样式 (应尽量避免,优先级最高,难以维护)。
<!DOCTYPE html>
<html>
<head>
<title>CSS Introduction</title>
<!-- 1. 外部样式表 -->
<link rel="stylesheet" href="styles.css" />
<!-- 2. 内部样式表 -->
<style>
p {
color: green;
}
</style>
</head>
<body>
<h1>Styled Heading</h1>
<p>This paragraph is styled by internal CSS.</p>
<!-- 3. 内联样式 -->
<p style="color: red; font-weight: bold;">
This paragraph uses inline style.
</p>
</body>
</html>
/* styles.css - 外部样式表文件 */
h1 {
color: navy;
text-decoration: underline;
}
3. 选择器 (Selectors)
选择器用于选取需要应用样式的 HTML 元素。
3.1 基本选择器
- 类型选择器 (Type Selector): 选择所有指定类型的 HTML 元素。
p {
/* 选择所有 <p> 元素 */
line-height: 1.6;
} - 类选择器 (Class Selector): 选择所有具有指定 class 属性的元素 (以
.开头)。.highlight {
/* 选择所有 class="highlight" 的元素 */
background-color: yellow;
} - ID 选择器 (ID Selector): 选择具有指定 id 属性的元素 (以
#开头,ID 在页面中应唯一)。#main-title {
/* 选择 id="main-title" 的元素 */
font-size: 32px;
font-weight: bold;
} - 通用选择器 (Universal Selector): 选择所有元素 (
*)。* {
/* 选择页面所有元素 (谨慎使用) */
box-sizing: border-box; /* 常用场景 */
} - 属性选择器 (Attribute Selector): 根据元素的属性或属性值选择。
/* 选择所有带有 href 属性的 <a> 元素 */
a[href] {
color: blue;
}
/* 选择所有 type="text" 的 <input> 元素 */
input[type="text"] {
border: 1px solid #ccc;
}
/* 选择所有 href 属性以 "https://" 开头的 <a> 元素 */
a[href^="https://"]
{
text-decoration: underline wavy;
}
/* 选择所有 class 属性包含 "icon" (作为一个独立的单词) 的元素 */
[class~="icon"] {
display: inline-block;
width: 1em;
height: 1em;
}
3.2 分组选择器 (Grouping Selector)
使用逗号 , 分隔,将相同的样式应用于多个选择器。
h1,
h2,
h3 {
font-family: "Arial", sans-serif;
color: #333;
}
3.3 组合选择器 (Combinators)
- 后代选择器 (Descendant Combinator) (空格): 选择某个元素内部的所有指定后代元素。
article p {
/* 选择 <article> 元素内部的所有 <p> 元素 */
color: gray;
} - 子选择器 (Child Combinator) (
>): 选择某个元素的直接子元素。ul > li {
/* 选择 <ul> 元素的直接子元素 <li> */
list-style-type: square;
} - 相邻兄弟选择器 (Adjacent Sibling Combinator) (
+): 选择紧跟在某个元素之后的同级元素。h2 + p {
/* 选择紧跟在 <h2> 之后的第一个同级 <p> 元素 */
margin-top: 0;
} - 通用兄弟选择器 (General Sibling Combinator) (
~): 选择某个元素之后的所有同级指定元素。h2 ~ p {
/* 选择 <h2> 之后的所有同级 <p> 元素 */
font-style: italic;
}
<!-- Selector Example HTML -->
<h1 id="main-title">Main Title</h1>
<p class="highlight">This is highlighted.</p>
<a href="https://example.com">Example Link</a>
<input type="text" placeholder="Your name" />
<article>
<h2>Article Heading</h2>
<p>First paragraph in article.</p>
<div>
<p>Second paragraph, nested deeper.</p>
</div>
<p>Third paragraph in article.</p>
</article>
<ul>
<li>Item 1</li>
<li>
Item 2
<ul>
<li>Nested Item</li>
</ul>
</li>
</ul>
4. 层叠与继承 (Cascade & Inheritance)
4.1 层叠 (Cascade)
当多个 CSS 规则应用于同一个元素时,浏览器通过层叠机制决定最终应用哪个样式。层叠顺序考虑以下因素(优先级从高到低):
- 来源和重要性:
- 浏览器默认样式
- 用户样式表
- 作者样式表 (开发者写的 CSS)
- 作者样式表中的
!important规则 - 用户样式表中的
!important规则 - 浏览器默认样式中的
!important规则 (通常我们主要关注作者样式表内部的规则)
- 特指度 (Specificity): 选择器的特殊性程度 (详见下一节)。
- 源顺序 (Source Order): 如果特指度相同,后定义的规则覆盖先定义的规则。
4.2 继承 (Inheritance)
某些 CSS 属性(如 color, font-family, font-size, line-height, text-align 等)会自动从父元素传递给子元素。其他属性(如 width, height, padding, margin, border, background 等)默认不继承。
可以使用以下值控制继承:
inherit: 强制继承父元素的属性值。initial: 将属性设置为其 CSS 标准定义的初始值。unset: 如果属性默认可继承,则表现像inherit;否则像initial。revert: 将属性设置为浏览器默认样式,如果存在的话,否则行为类似unset。
<div class="parent">
Parent Text
<p class="child">Child Paragraph</p>
<p class="child force-inherit-border">Child with forced border inherit</p>
</div>
.parent {
color: blue; /* color 会被继承 */
border: 2px solid red; /* border 不会被继承 */
font-size: 20px; /* font-size 会被继承 */
}
.child {
/* 自动继承了 color: blue 和 font-size: 20px */
/* 没有继承 border */
border: initial; /* 重置为 border 的初始值 (通常是 none) */
}
.force-inherit-border {
border: inherit; /* 强制继承父元素的 border 样式 */
}
5. 特指度 (Specificity)
特指度是浏览器用来决定当多个规则指向同一个元素时,哪个规则最相关(优先级更高)的算法。它通常表示为一个四元组 (a, b, c, d):
- a: 内联样式 (1, 0, 0, 0) -
style属性。 - b: ID 选择器 (0, 1, 0, 0) -
#id. - c: 类选择器 (
.class), 属性选择器 ([type="text"]), 伪类 (:hover) (0, 0, 1, 0). - d: 类型选择器 (
p), 伪元素 (::before) (0, 0, 0, 1).
通用选择器 * 和组合器 +, >, ~, 不增加特指度。:not() 伪类本身不增加特指度,但其参数内的选择器会计算特指度。
比较时,从左到右比较 (a > b > c > d)。!important 规则会覆盖所有特指度计算,但应避免滥用。
<div id="content">
<p class="info important">This is important info.</p>
</div>
<style>
/* d=1 (0,0,0,1) */
p {
color: black;
}
/* c=1 (0,0,1,0) */
.info {
color: blue;
}
/* c=2 (0,0,2,0) */
p.important {
color: green;
} /* 更具体 */
/* c=1, d=1 (0,0,1,1) -- Note: Type selector adds to specificity here */
div p.info {
color: purple;
} /* 比 p.important 更具体 */
/* b=1 (0,1,0,0) */
#content .info {
color: red;
} /* ID 使其非常具体 */
/* a=1 (1,0,0,0) - 在 HTML 的 style 属性中 */
/* <p class="info important" style="color: orange;">...</p> */
</style>
最终 #content .info 的 color: red 会生效,除非有内联样式 style="color: orange;"。
6. 盒子模型 (Box Model)
每个 HTML 元素都可以看作一个矩形的盒子。盒子模型描述了这些盒子的大小和它们之间的关系。主要包括:
- Content: 元素内容的区域 (文本、图片等)。其大小由
width和height属性控制。 - Padding: 内边距,内容区与边框之间的空间,是透明的。由
padding-top,padding-right,padding-bottom,padding-left或padding简写属性控制。 - Border: 边框,包围内边距和内容区。由
border-width,border-style,border-color或border简写属性控制。 - Margin: 外边距,边框之外的空间,用于控制元素与其他元素之间的距离,是透明的。由
margin-top,margin-right,margin-bottom,margin-left或margin简写属性控制。
box-sizing 属性
content-box(默认值):width和height只包含内容区的尺寸。Padding 和 Border 会增加盒子的实际总尺寸。- 总宽度 =
width+padding-left+padding-right+border-left-width+border-right-width - 总高度 =
height+padding-top+padding-bottom+border-top-width+border-bottom-width
- 总宽度 =
border-box:width和height包含内容区、内边距 (Padding) 和边框 (Border)。Padding 和 Border 不会增加盒子的总尺寸。- 总宽度 =
width - 总高度 =
height(通常推荐设置为border-box以简化布局计算)
- 总宽度 =
<div class="box content-box-example">Content Box</div>
<div class="box border-box-example">Border Box</div>
/* 通常建议全局设置 */
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit; /* 让所有元素继承 html 的 box-sizing */
}
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 10px solid blue;
margin: 15px;
background-color: lightgray;
}
.content-box-example {
box-sizing: content-box;
/* 实际占用宽度 = 200 + 20*2 + 10*2 = 260px */
/* 实际占用高度 = 100 + 20*2 + 10*2 = 160px */
}
.border-box-example {
box-sizing: border-box;
/* 实际占用宽度 = 200px */
/* 实际占用高度 = 100px */
/* 内容区宽度会被压缩 = 200 - 20*2 - 10*2 = 140px */
/* 内容区高度会被压缩 = 100 - 20*2 - 10*2 = 40px */
}
7. 布局 (Layout)
CSS 布局用于控制元素在页面上的排列方式。
7.1 display 属性
决定元素的呈现方式(块级、行内等)以及其子元素的布局方式。
block: 元素呈现为块级元素。通常独占一行,可以设置width,height,margin,padding。 (e.g.,<div>,<p>,<h1>)inline: 元素呈现为行内元素。不独占一行,width,height通常无效,垂直margin,padding可能无效或表现不同。 (e.g.,<span>,<a>,<img>)inline-block: 元素呈现为行内块级元素。像inline一样不换行,但像block一样可以设置width,height,margin,padding。none: 元素不显示,并且不占据空间 (与visibility: hidden不同,后者会占据空间)。flex: 启用 Flexbox 布局模式,用于一维布局 (行或列)。grid: 启用 Grid 布局模式,用于二维布局 (行和列)。table,table-row,table-cell等: 模拟表格布局。
<div class="block-el">Block Element</div>
<span class="inline-el">Inline Element 1</span>
<span class="inline-el">Inline Element 2</span>
<div class="inline-block-el">Inline Block 1</div>
<div class="inline-block-el">Inline Block 2</div>
<div class="hidden-el">Hidden Element</div>
.block-el {
display: block;
background: lightcoral;
padding: 10px;
margin-bottom: 5px;
}
.inline-el {
display: inline;
background: lightblue;
padding: 10px; /* 垂直 padding 可能影响行高,但不推开上下元素 */
margin: 10px; /* 垂直 margin 无效 */
}
.inline-block-el {
display: inline-block;
background: lightgreen;
width: 150px;
height: 50px;
padding: 10px;
margin: 5px;
}
.hidden-el {
display: none;
background: yellow; /* 不会显示 */
}
7.2 position 属性
定义元素的定位方式。配合 top, right, bottom, left 属性(偏移属性)和 z-index 属性(堆叠顺序)使用。
static(默认值): 元素遵循正常的文档流布局。偏移属性无效。relative: 元素相对于其在正常文档流中的位置进行定位,不脱离文档流(仍占据原始空间)。偏移属性使其移动,但不会影响其他元素的位置。absolute: 元素相对于其最近的 已定位 (非static) 的祖先元素进行定位。如果找不到,则相对于初始包含块(通常是<html>)。元素会脱离文档流。fixed: 元素相对于浏览器视口 (viewport) 进行定位,即使页面滚动,它也保持在相同位置。元素会脱离文档流。sticky: 元素在跨越特定阈值前(通常是滚动超过某个点)表现为relative,之后表现为fixed。需要指定top,right,bottom或left中的至少一个。不完全脱离文档流。
<div class="container">
<div class="box static">Static</div>
<div class="box relative">
Relative
<div class="absolute-child">Absolute Child</div>
</div>
<div class="box absolute">Absolute</div>
<div class="box fixed">Fixed</div>
<div class="box sticky">Sticky</div>
</div>
<div style="height: 1000px;">Scrollable Area</div>
<!-- To demonstrate fixed/sticky -->
.container {
position: relative; /* Needed for absolute positioning relative to this container */
border: 2px dashed gray;
padding: 10px;
height: 400px; /* Give container some height */
}
.box {
width: 100px;
height: 100px;
background-color: rgba(255, 0, 0, 0.7);
color: white;
padding: 10px;
margin-bottom: 10px;
}
.static {
position: static;
background-color: lightgray;
color: black;
}
.relative {
position: relative;
top: 20px;
left: 20px;
background-color: lightblue;
z-index: 1; /* Higher z-index appears on top */
}
.absolute-child {
position: absolute;
bottom: 5px;
right: 5px;
background: darkblue;
width: 50px;
height: 30px;
font-size: 12px;
}
.absolute {
position: absolute;
top: 50px;
right: 10px;
background-color: lightgreen;
}
.fixed {
position: fixed;
bottom: 10px;
right: 10px;
background-color: orange;
z-index: 100; /* High z-index to stay on top */
}
.sticky {
position: sticky;
top: 0; /* Required for sticky positioning */
background-color: purple;
z-index: 50;
}
7.3 Flexbox 布局 (display: flex)
一种用于在一维空间(行或列)内对齐和分布项目的高效布局模型。
- 容器属性 (Container Properties):
display: flex;或inline-flex;flex-direction: 主轴方向 (row,row-reverse,column,column-reverse)。flex-wrap: 项目是否换行 (nowrap,wrap,wrap-reverse)。justify-content: 主轴对齐方式 (flex-start,flex-end,center,space-between,space-around,space-evenly)。align-items: 交叉轴对齐方式(单行) (stretch,flex-start,flex-end,center,baseline)。align-content: 交叉轴对齐方式(多行) (stretch,flex-start,flex-end,center,space-between,space-around)。gap,row-gap,column-gap: 项目间距。
- 项目属性 (Item Properties):
order: 项目排列顺序。flex-grow: 项目放大比例。flex-shrink: 项目缩小比例。flex-basis: 项目在主轴上的基础大小。flex:flex-grow,flex-shrink,flex-basis的简写。align-self: 单个项目在交叉轴上的对齐方式 (覆盖align-items)。
<div class="flex-container">
<div class="flex-item item1">Item 1</div>
<div class="flex-item item2">Item 2</div>
<div class="flex-item item3">Item 3</div>
</div>
.flex-container {
display: flex;
flex-direction: row; /* Default */
justify-content: space-around; /* Distribute items along the main axis */
align-items: center; /* Align items along the cross axis */
flex-wrap: wrap; /* Allow items to wrap */
gap: 10px; /* Space between items */
background-color: #eee;
padding: 10px;
height: 200px; /* Give container height */
border: 1px solid #ccc;
}
.flex-item {
background-color: dodgerblue;
color: white;
padding: 20px;
text-align: center;
/* flex-grow: 1; */ /* Uncomment to make items share space equally */
/* flex-basis: 150px; */ /* Define base size */
}
.item1 {
/* order: 2; */ /* Change order */
/* flex-grow: 2; */ /* Make this item grow twice as fast */
}
.item2 {
/* order: 1; */
/* align-self: flex-start; */ /* Align this item differently */
}
.item3 {
/* order: 3; */
}
7.4 Grid 布局 (display: grid)
一种强大的二维布局系统,可以同时控制行和列。
- 容器属性 (Container Properties):
display: grid;或inline-grid;grid-template-columns,grid-template-rows: 定义网格的列宽和行高 (e.g.,1fr 2fr,repeat(3, 100px),auto 1fr auto)。grid-template-areas: 使用命名区域定义布局。gap,row-gap,column-gap: 网格线之间的间距。justify-items: 网格项目沿行轴(内联轴)的对齐方式。align-items: 网格项目沿列轴(块轴)的对齐方式。justify-content: 整个网格在容器内沿行轴的对齐方式(当网格总尺寸小于容器时)。align-content: 整个网格在容器内沿列轴的对齐方式(当网格总尺寸小于容器时)。
- 项目属性 (Item Properties):
grid-column-start,grid-column-end,grid-row-start,grid-row-end: 定义项目占据的网格线。grid-column,grid-row: 上述属性的简写 (e.g.,1 / 3,span 2)。grid-area: 将项目分配到grid-template-areas定义的命名区域,或者是上述四个位置属性的简写。justify-self: 单个项目沿行轴的对齐方式 (覆盖justify-items)。align-self: 单个项目沿列轴的对齐方式 (覆盖align-items)。
<div class="grid-container">
<div class="grid-item header">Header</div>
<div class="grid-item sidebar">Sidebar</div>
<div class="grid-item main">Main Content</div>
<div class="grid-item footer">Footer</div>
</div>
.grid-container {
display: grid;
/* Define 3 columns: 1fr (fraction), 3fr, 1fr */
grid-template-columns: 1fr 3fr 1fr;
/* Define rows: auto height for header/footer, 1fr for main area */
grid-template-rows: auto 1fr auto;
/* Define named areas */
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
gap: 15px; /* Gap between grid items */
height: 400px; /* Give container height */
border: 1px solid #ccc;
padding: 10px;
background-color: #f9f9f9;
}
.grid-item {
background-color: lightcoral;
color: white;
padding: 20px;
text-align: center;
border: 1px solid #aaa;
}
/* Assign items to named areas */
.header {
grid-area: header;
background-color: lightblue;
}
.sidebar {
grid-area: sidebar;
background-color: lightgreen;
}
.main {
grid-area: main;
background-color: lightgoldenrodyellow;
color: black;
}
.footer {
grid-area: footer;
background-color: lightsalmon;
}
/* Example of positioning using line numbers (alternative to areas) */
/*
.header { grid-column: 1 / 4; grid-row: 1; }
.sidebar { grid-column: 1 / 2; grid-row: 2; }
.main { grid-column: 2 / 4; grid-row: 2; }
.footer { grid-column: 1 / 4; grid-row: 3; }
*/
8. 颜色与背景 (Colors & Backgrounds)
8.1 颜色值
- 命名颜色:
red,blue,transparent等。 - HEX:
#RRGGBB或#RGB(e.g.,#ff0000,#f00)。 - HEX with Alpha:
#RRGGBBAA或#RGBA(e.g.,#ff000080,#f008)。 - RGB:
rgb(red, green, blue)(值范围 0-255)。 - RGBA:
rgba(red, green, blue, alpha)(alpha 范围 0-1)。 - HSL:
hsl(hue, saturation, lightness)(色相 0-360, 饱和度/亮度 0%-100%)。 - HSLA:
hsla(hue, saturation, lightness, alpha)(alpha 范围 0-1)。
8.2 背景属性
background-color: 设置背景颜色。background-image: 设置背景图片 (url('path/to/image.jpg'))。可以设置多个背景图片,用逗号分隔。background-repeat: 背景图片是否重复 (repeat,repeat-x,repeat-y,no-repeat,space,round)。background-position: 背景图片初始位置 (e.g.,center,top left,50% 50%,20px 10px)。background-size: 背景图片尺寸 (auto,cover,contain,<length>,<percentage>)。background-attachment: 背景图片是否随滚动移动 (scroll,fixed,local)。background-origin: 定位区域参照 (padding-box,border-box,content-box)。background-clip: 绘制区域 (padding-box,border-box,content-box,text)。background: 所有背景属性的简写。
<div class="background-example">This div has a styled background.</div>
.background-example {
width: 300px;
height: 200px;
padding: 20px;
border: 5px dashed hsla(120, 100%, 50%, 0.5); /* Green dashed border with alpha */
color: #333; /* Dark gray text color */
/* Using background shorthand */
background:
/* Layer 1: Gradient (acts like an image) */ linear-gradient(
rgba(255, 255, 255, 0.7),
rgba(255, 255, 255, 0.2)
),
/* Layer 2: Image */ url("path/to/small-icon.png") no-repeat top right /
30px auto, /* Positioned, sized */ /* Layer 3: Base color */ lightblue; /* Base color */
/* Individual properties example: */
/* background-color: lightblue; */
/* background-image: url('path/to/image.jpg'); */
/* background-repeat: no-repeat; */
/* background-position: center; */
/* background-size: cover; */
/* background-attachment: fixed; */
}
9. 文本与字体样式 (Text & Fonts)
9.1 常用文本属性
color: 文本颜色。text-align: 文本水平对齐方式 (left,right,center,justify)。line-height: 行高。text-decoration: 文本装饰 (none,underline,overline,line-through,blink)。可以组合。text-transform: 文本大小写转换 (none,capitalize,uppercase,lowercase)。text-indent: 首行缩进。letter-spacing: 字符间距。word-spacing: 单词间距。white-space: 处理元素内的空白 (normal,nowrap,pre,pre-wrap,pre-line)。text-shadow: 文本阴影 (h-shadow v-shadow blur-radius color)。
9.2 常用字体属性
font-family: 字体族。指定一个或多个字体名称,用逗号分隔,最后通常跟一个通用字体族 (serif,sans-serif,monospace,cursive,fantasy)。font-size: 字体大小。font-weight: 字体粗细 (normal,bold,100-900)。font-style: 字体样式 (normal,italic,oblique)。font-variant: 小型大写字母 (normal,small-caps)。font: 所有字体属性的简写 (有特定顺序和要求)。
9.3 @font-face
允许使用自定义字体。
@font-face {
font-family: "MyCustomFont"; /* Define a name for the font */
src: url("fonts/mycustomfont.woff2") format("woff2"), /* Modern format */
url("fonts/mycustomfont.woff") format("woff"); /* Older format */
font-weight: normal;
font-style: normal;
}
body {
font-family: "MyCustomFont", "Helvetica Neue", Arial, sans-serif; /* Use custom font first */
}
.special-text {
color: navy;
font-size: 1.2em; /* Relative size */
font-weight: bold;
line-height: 1.5;
text-align: center;
text-decoration: underline dotted red;
text-transform: uppercase;
letter-spacing: 1px;
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
}
10. 单位与值 (Units & Values)
10.1 绝对单位
尺寸固定,不随其他因素改变。
px: 像素 (Pixel)。最常用。pt: 点 (Point) (1pt = 1/72 inch)。常用于印刷。cm,mm,in: 物理单位。
10.2 相对单位
尺寸相对于其他值确定。
%: 相对于父元素或包含块的百分比。em: 相对于当前元素的font-size。如果用于font-size自身,则相对于父元素的font-size。rem: (Root em) 相对于根元素 (<html>) 的font-size。常用于全局尺寸调整。vw: 相对于视口宽度 (Viewport Width) 的 1%。vh: 相对于视口高度 (Viewport Height) 的 1%。vmin,vmax: 相对于视口宽度或高度中较小/较大者的 1%。
html {
font-size: 16px; /* Base font size for rem calculation */
}
.container {
width: 80%; /* 80% of parent width */
font-size: 1.2em; /* 1.2 times parent font size */
padding: 1rem; /* 1 times root font size (16px) */
}
.sidebar {
width: 25vw; /* 25% of viewport width */
height: 100vh; /* Full viewport height */
}
h1 {
font-size: 2rem; /* 2 * 16px = 32px */
margin-bottom: 1em; /* 1 * 32px = 32px (relative to its own font-size) */
}
11. 伪类与伪元素 (Pseudo-classes & Pseudo-elements)
11.1 伪类 (Pseudo-classes)
以单冒号 : 开头,用于定义元素的特殊状态。
- 用户操作状态:
:hover(鼠标悬停),:active(元素激活),:focus(元素获得焦点),:focus-within(元素或其后代获得焦点)。 - 结构性伪类:
:first-child,:last-child,:nth-child(n),:nth-last-child(n),:only-child,:empty,:root。 - 链接状态:
:link(未访问链接),:visited(已访问链接)。 - 表单状态:
:checked,:disabled,:enabled,:required,:optional. - 逻辑:
:not(selector).
/* Style links */
a:link {
color: blue;
}
a:visited {
color: purple;
}
a:hover {
text-decoration: underline;
color: red;
}
a:active {
color: orange;
}
/* Style focused inputs */
input:focus {
border-color: dodgerblue;
outline: none; /* Often remove default outline and provide custom focus style */
box-shadow: 0 0 5px rgba(30, 144, 255, 0.5);
}
/* Style every odd list item */
li:nth-child(odd) {
background-color: #f2f2f2;
}
/* Style the first paragraph inside an article */
article p:first-child {
font-weight: bold;
}
/* Style buttons that are not disabled */
button:not(:disabled):hover {
background-color: #ddd;
}
11.2 伪元素 (Pseudo-elements)
以双冒号 :: 开头(旧版 CSS 也接受单冒号 :),用于为元素的特定部分设置样式。
::before: 在元素内容之前插入生成的内容 (需要content属性)。::after: 在元素内容之后插入生成的内容 (需要content属性)。::first-line: 选择元素的第一行文本。::first-letter: 选择元素的第一个字母。::selection: 选择用户高亮选中的部分。::placeholder: 选择表单元素的占位文本。
/* Add quotes around blockquote elements */
blockquote::before {
content: '"';
font-size: 2em;
margin-right: 5px;
}
blockquote::after {
content: '"';
font-size: 2em;
margin-left: 5px;
}
/* Style the first letter of paragraphs */
p::first-letter {
font-size: 1.5em;
font-weight: bold;
color: firebrick;
float: left; /* Common effect */
margin-right: 4px;
}
/* Style selected text */
::selection {
background-color: yellow;
color: black;
}
/* Style input placeholder */
input::placeholder {
color: #aaa;
font-style: italic;
}
12. 过渡与动画 (Transitions & Animations)
12.1 过渡 (transition)
使 CSS 属性值的变化平滑地进行,而不是瞬间改变。
transition-property: 指定应用过渡的 CSS 属性名称 (e.g.,width,color,all)。transition-duration: 过渡效果持续时间 (e.g.,0.5s,300ms)。transition-timing-function: 过渡速度曲线 (linear,ease,ease-in,ease-out,ease-in-out,cubic-bezier(...))。transition-delay: 过渡效果开始前的延迟时间。transition: 上述属性的简写。
<button class="transition-button">Hover Me</button>
.transition-button {
padding: 10px 20px;
background-color: steelblue;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
/* Define transitions */
transition-property: background-color, transform;
transition-duration: 0.3s;
transition-timing-function: ease-out;
/* Shorthand: */
/* transition: background-color 0.3s ease-out, transform 0.3s ease-out; */
/* Or apply to all properties: */
/* transition: all 0.3s ease-out; */
}
.transition-button:hover {
background-color: orangered;
transform: scale(1.1) translateY(-2px); /* Scale up and move slightly up */
}
12.2 动画 (animation 和 @keyframes)
创建更复杂的动画序列。
@keyframes: 定义动画序列中的关键帧(中间状态)。animation属性: 将@keyframes应用到元素上,并配置动画。animation-name:@keyframes规则的名称。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: 控制动画播放/暂停 (running,paused)。animation: 上述属性的简写。
<div class="spinner"></div>
/* Define the animation sequence */
@keyframes spin {
from {
/* or 0% */
transform: rotate(0deg);
}
to {
/* or 100% */
transform: rotate(360deg);
}
}
@keyframes pulse {
0% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.5;
transform: scale(1.1);
}
100% {
opacity: 1;
transform: scale(1);
}
}
.spinner {
width: 50px;
height: 50px;
border: 5px solid lightgray;
border-top-color: dodgerblue; /* Make one part different */
border-radius: 50%; /* Make it round */
/* Apply the animation */
animation-name: spin;
animation-duration: 1s;
animation-timing-function: linear;
animation-iteration-count: infinite; /* Keep spinning */
/* Example of applying multiple animations */
/* animation: spin 1s linear infinite, pulse 2s ease-in-out infinite; */
}
13. 响应式设计与媒体查询 (Responsive Design & Media Queries)
13.1 响应式设计 (Responsive Design)
使网站布局能够适应不同设备的屏幕尺寸和特性(如手机、平板、桌面),提供良好的用户体验。关键技术包括:
- 流式布局 (Fluid Grids): 使用相对单位(如
%)创建网格布局。 - 弹性图片/媒体 (Flexible Images/Media): 使用
max-width: 100%; height: auto;使图片等比例缩放。 - 媒体查询 (Media Queries): 根据设备特性(如视口宽度、方向、分辨率)应用不同的 CSS 规则。
13.2 媒体查询 (@media)
允许内容在不同条件下应用不同的样式。
/* Default styles (mobile-first approach recommended) */
body {
font-size: 16px;
line-height: 1.5;
}
.container {
width: 95%; /* Fluid width */
margin: 0 auto;
}
img {
max-width: 100%; /* Make images responsive */
height: auto;
}
/* Styles for tablets and larger (e.g., min-width 768px) */
@media (min-width: 768px) {
body {
font-size: 17px;
}
.container {
width: 90%;
}
/* Example: Change layout to multi-column */
.columns {
display: flex;
gap: 20px;
}
.main-content {
flex: 2; /* Takes 2/3 space */
}
.sidebar {
flex: 1; /* Takes 1/3 space */
}
}
/* Styles for desktops and larger (e.g., min-width 1024px) */
@media (min-width: 1024px) {
body {
font-size: 18px;
}
.container {
width: 85%;
max-width: 1200px; /* Add a max-width for very large screens */
}
}
/* Example: Targeting specific features */
@media (orientation: landscape) {
/* Styles for landscape mode */
.some-element {
/* ... */
}
}
@media print {
/* Styles for printing */
body {
font-family: serif;
color: black;
}
a::after {
content: " (" attr(href) ")"; /* Show URLs when printing */
}
.no-print {
display: none; /* Hide elements not needed for print */
}
}
14. CSS 变量 (Custom Properties)
也称为 CSS 自定义属性,允许你定义可以在整个文档中重用的值。
- 声明: 使用
--前缀定义在元素上 (通常在:root伪类上定义全局变量)。 - 使用: 使用
var()函数引用。
/* Define variables globally on the :root (<html> element) */
:root {
--primary-color: steelblue;
--secondary-color: #f5f5f5;
--text-color: #333;
--base-font-size: 16px;
--spacing-unit: 10px;
}
/* Use variables */
body {
font-size: var(--base-font-size);
color: var(--text-color);
background-color: var(--secondary-color);
}
h1 {
color: var(--primary-color);
margin-bottom: calc(var(--spacing-unit) * 2); /* Use in calculations */
}
button {
background-color: var(--primary-color);
color: white;
padding: var(--spacing-unit) calc(var(--spacing-unit) * 1.5);
border: none;
border-radius: calc(var(--spacing-unit) / 2);
}
/* Variables can be overridden in specific scopes */
.themed-section {
--primary-color: darkgreen; /* Override for this section */
background-color: #e8f5e9;
}
.themed-section h2 {
color: var(--primary-color); /* Will use darkgreen here */
}
/* Providing fallback values for var() */
.element {
color: var(
--undefined-variable,
black
); /* Uses black if --undefined-variable is not set */
}