css

110 阅读22分钟

选择器

CSS 选择器用于选择需要添加样式的 HTML 元素。

基本选择器

  1. 元素选择器(标签选择器)
p {
  color: blue;
}
  • 选择所有 <p> 元素
  1. 类选择器 (Class Selector)
.intro {
  font-size: 16px;
}
  • 选择所有 class="intro" 的元素
  1. ID 选择器
#header {
  background: #333;
}
  • 选择 id="header" 的元素(一个页面中 ID 应唯一)
  1. 通配符选择器
* {
  margin: 0;
  padding: 0;
}
  • 选择所有元素
  1. 属性选择器
[title] {
  color: purple;
}

[type="text"] {
  border: 1px solid #ccc;
}

[href^="https"] {
  color: green;
}

[href$=".pdf"] {
  background: url(pdf-icon.png);
}

[class*="btn-"] {
  padding: 5px 10px;
}
  • 根据属性及其值选择元素

组合选择器

  1. 后代选择器 (空格)
div p {
  line-height: 1.5;
}
  • 选择 <div> 内部的所有 <p> 元素(包括嵌套多层的)
  1. 子元素选择器 (>)
ul > li {
  list-style: none;
}
  • 只选择直接子元素(不包含孙子元素)
  1. 相邻兄弟选择器 (+)
h2 + p {
  margin-top: 0;
} 
  • 选择紧接在 h2 后的第一个 <p> 兄弟元素
  1. 通用兄弟选择器 (~)
h2 ~ p {
  color: gray;
}
  • 选择 h2 后面的所有 <p> 兄弟元素
  1. 分组选择器 (,)
h1, h2, h3 {
  font-family: sans-serif;
}
  • 同时选择多个元素

伪类选择器

  1. 链接相关
a:link { color: blue; }    /* 未访问链接 */
a:visited { color: purple; } /* 已访问链接 */
a:hover { text-decoration: underline; } /* 鼠标悬停 */
a:active { color: red; }  /* 点击时 */
  1. 表单相关
input:focus {
  border-color: blue;
}

input:disabled {
  opacity: 0.5;
}

input:checked + label {
  font-weight: bold;
}
  1. 结构伪类
li:first-child { background: #eee; }  /* 第一个子元素 */
li:last-child { border-bottom: none; } /* 最后一个子元素 */

tr:nth-child(odd) { background: #f9f9f9; } /* 奇数行 */
tr:nth-child(even) { background: #fff; } /* 偶数行 */
tr:nth-child(3n) { color: red; } /* 每第3个 */

p:only-child { font-size: 1.2em; } /* 唯一子元素 */

:root { --main-color: #06c; } /* 选择文档根元素(html) */
  1. 其他伪类
p:empty { display: none; } /* 没有子元素的元素 */

img:target { border: 2px solid black; } /* 当前活动的目标元素 */

:not(p) { margin: 10px; } /* 非p元素 */

伪元素选择器

p::first-line { font-weight: bold; } /* 第一行 */
p::first-letter { font-size: 2em; } /* 第一个字母 */

::before {
  content: "→ ";
  color: green;
} /* 在元素前插入内容 */

::after {
  content: " ←";
  color: red;
} /* 在元素后插入内容 */

::selection {
  background: yellow;
  color: black;
} /* 用户选中的文本 */

选择器优先级

当多个规则应用于同一元素时,CSS 根据以下优先级决定应用哪个样式:

  1. !important - 最高优先级
p { color: red !important; }
  1. 内联样式 - <p style="color: blue;">
  2. ID 选择器 - #content
  3. 类/属性/伪类选择器 - .intro, [type="text"], :hover
  4. 元素/伪元素选择器 - p, ::before
  5. 通配符/继承的样式 - *, 继承的属性

计算规则:

  • 内联样式:1000
  • ID:100
  • 类/属性/伪类:10
  • 元素/伪元素:1
  • 通配符:0

比较各选择器的总分,分数高的优先级高。

最佳实践

  1. 避免过度使用 ID 选择器(难以复用)
  2. 避免使用 !important(难以覆盖)
  3. 保持选择器简洁(避免 .nav ul li a 这样的长选择器)
  4. 合理使用 BEM 等命名规范提高可维护性
  5. 利用 CSS 预处理器(如 Sass)的嵌套功能提高可读性

通过合理组合这些选择器,可以精确地定位和样式化页面上的任何元素。

BFC

BFC(Block Formatting Context,块级格式化上下文)是 CSS 视觉渲染的一部分,它决定了元素如何对其内容进行布局,以及与其他元素的关系和相互作用。

什么是 BFC

BFC 是 Web 页面中一个独立的渲染区域,具有以下特性:

  • 内部的盒子会在垂直方向上一个接一个地放置
  • 盒子垂直方向的距离由 margin 决定,属于同一个 BFC 的两个相邻盒子的 margin 会发生重叠
  • BFC 的区域不会与浮动盒子重叠
  • BFC 就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素
  • 计算 BFC 的高度时,浮动元素也参与计算

如何创建 BFC

一个元素满足以下任意一个条件就会创建 BFC:

  1. 根元素(<html>
  2. 浮动元素(float 值不为 none)
  3. 绝对定位元素(position 为 absolute 或 fixed)
  4. display 值为 inline-block、table-cell、table-caption、flex、inline-flex、grid、inline-grid
  5. overflow 值不为 visible 的块元素(hidden、auto、scroll)
  6. contain 值为 layout、content 或 paint 的元素
  7. 多列容器(column-count 或 column-width 不为 auto,包括 column-count: 1)
  8. column-span: all 的元素

BFC 的常见应用

  1. 解决 margin 重叠问题
<div class="container">
  <p>段落1</p>
  <p>段落2</p>
</div>

p {
  margin: 20px 0;
  background: #f00;
}

/* 创建 BFC 解决 margin 重叠 */
.container {
  overflow: hidden; /* 触发 BFC */
}
  1. 清除浮动(防止父元素高度塌陷)
<div class="parent">
  <div class="float-child">浮动元素</div>
</div>

.float-child {
  float: left;
  width: 100px;
  height: 100px;
  background: #09f;
}

/* 创建 BFC 清除浮动 */
.parent {
  overflow: hidden; /* 触发 BFC */
  background: #f0f0f0;
}
  1. 阻止元素被浮动元素覆盖
<div class="float-box">浮动盒子</div>
<div class="normal-box">普通盒子</div>

.float-box {
  float: left;
  width: 200px;
  height: 150px;
  background: #09f;
}

.normal-box {
  height: 200px;
  background: #f60;
  
  /* 创建 BFC 避免被浮动元素覆盖 */
  overflow: hidden;
}

BFC 的特性详解

  1. 内部盒子垂直排列
  • 在 BFC 中,盒子从顶部开始垂直排列,一个接一个。
  1. margin 重叠只发生在同一 BFC
  • 属于同一个 BFC 的两个相邻盒子的垂直 margin 会发生重叠,不同 BFC 的不会重叠。
  1. BFC 区域不与浮动元素重叠
  • BFC 会避开浮动元素,可以用来实现两栏布局。
  1. BFC 包含浮动元素
  • 计算 BFC 高度时,浮动子元素也参与计算,解决了父元素高度塌陷问题。
  1. BFC 是独立容器
  • BFC 内部的元素不会影响外部元素,反之亦然。

BFC 与布局

  1. 自适应两栏布局
<div class="left">左侧浮动</div>
<div class="right">右侧自适应</div>

.left {
  float: left;
  width: 200px;
  height: 300px;
  background: #09f;
}

.right {
  overflow: hidden; /* 触发 BFC */
  height: 300px;
  background: #f60;
}
  1. 防止文字环绕
<div class="float-img"></div>
<p class="text">很多文字内容...</p>

.float-img {
  float: left;
  width: 100px;
  height: 100px;
  background: #09f;
}

.text {
  overflow: hidden; /* 触发 BFC,文字不再环绕 */
}

BFC 的创建方法比较

方法副作用适用场景
float: left/right元素变为浮动元素需要浮动的元素
position: absolute/fixed脱离文档流绝对定位元素
display: inline-block变为行内块需要行内块特性的元素
overflow: hidden/auto/scroll可能隐藏内容或显示滚动条最常用,副作用小
display: flex/grid变为弹性或网格布局现代布局方案

最佳实践:通常使用 overflow: hidden 来创建 BFC,因为它的副作用最小,除非有特殊需求。

理解 BFC 对于解决 CSS 中的许多布局问题非常有帮助,特别是处理浮动、margin 重叠和定位问题时。

盒模型

盒模型(Box Model)是 CSS 布局的基础概念,它描述了元素在页面中所占的空间以及如何计算这些空间。

盒模型组成

每个 HTML 元素都被视为一个矩形盒子,由以下四部分组成:

  1. 内容区(Content) - 包含实际内容(文本、图片等)
  2. 内边距(Padding) - 内容与边框之间的透明区域
  3. 边框(Border) - 围绕内容和内边距的边框
  4. 外边距(Margin) - 边框外的透明区域,用于分隔相邻元素

标准盒模型 vs 怪异盒模型

CSS 中有两种盒模型计算方式:

  1. 标准盒模型(content-box) - 默认值
box-sizing: content-box;
  • 宽度计算:width = 内容宽度
  • 总宽度 = width + padding + border + margin
  • 总高度 = height + padding + border + margin
  1. 怪异盒模型(border-box)
box-sizing: border-box;
  • 宽度计算:width = 内容宽度 + padding + border
  • 总宽度 = width + margin
  • 总高度 = height + margin

示例比较

.box {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
  margin: 10px;
}
  • content-box

    • 内容宽度:200px
    • 总宽度:200 + 20* 2 + 5* 2 + 10* 2 = 270px
  • border-box

    • 内容宽度:200 - 20* 2 - 5* 2 = 150px
    • 总宽度:200 + 10*2 = 220px

盒模型属性详解

  1. 内容区(Content)
width: 200px;       /* 宽度 */
height: 100px;      /* 高度 */
min-width: 300px;   /* 最小宽度 */
max-height: 500px;  /* 最大高度 */
  1. 内边距(Padding)
padding: 10px;                  /* 所有边 */
padding: 10px 20px;             /* 上下 | 左右 */
padding: 10px 20px 30px;        /* 上 | 左右 | 下 */
padding: 10px 20px 30px 40px;   /* 上 | 右 | 下 | 左 */

/* 单独设置 */
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
  1. 边框(Border)
border: 1px solid #000;  /* 宽度 | 样式 | 颜色 */

/* 单独设置 */
border-width: 1px 2px 3px 4px;
border-style: solid dashed dotted double;
border-color: red green blue black;

/* 单边边框 */
border-top: 2px dashed #f00;
border-right: none; /* 无右边框 */

/* 圆角 */
border-radius: 10px;       /* 所有角 */
border-radius: 10px 20px;  /* 左上右下 | 右上左下 */
border-radius: 10px 20px 30px 40px; /* 左上 | 右上 | 右下 | 左下 */
  1. 外边距(Margin)
margin: 10px;                 /* 所有边 */
margin: 10px 20px;            /* 上下 | 左右 */
margin: 10px 20px 30px;       /* 上 | 左右 | 下 */
margin: 10px 20px 30px 40px;  /* 上 | 右 | 下 | 左 */

/* 单独设置 */
margin-top: 10px;
margin-right: auto; /* 水平居中常用 */
margin-bottom: 30px;
margin-left: 40px;

特殊行为与注意事项

1. margin 重叠(Collapsing Margins)

垂直方向上相邻元素的 margin 会发生重叠:

  • 取两者中较大的 margin 值
  • 只发生在块级元素(不包括浮动和绝对定位元素)
  • 父子元素的第一个/最后一个子元素的 margin 也会与父元素重叠

解决方案

  • 使用 padding 替代
  • 创建 BFC(如设置 overflow: hidden
  • 添加透明边框 border: 1px solid transparent

2. 负 margin 的应用

/* 元素重叠 */
.overlap {
  margin-top: -20px;
}

/* 居中技巧 */
.center {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -100px; /* 元素宽度的一半 */
  margin-top: -50px;   /* 元素高度的一半 */
  width: 200px;
  height: 100px;
}

3. 行内元素的盒模型

  • width 和 height 无效
  • 垂直方向的 padding 和 margin 不会影响行高(不会推开其他行)
  • 水平方向的 padding 和 margin 有效

4. 盒模型调试技巧

使用浏览器开发者工具:

  • 查看元素盒模型图示
  • 实时修改属性值测试效果
  • 查看计算后的最终样式

实际应用建议

  1. 全局设置 border-box:
* {
  box-sizing: border-box;
}

这样更符合直觉,便于计算元素尺寸。

  1. margin 初始化:
body {
  margin: 0;
}

去除浏览器默认 margin。

  1. 灵活使用百分比:
.container {
  width: 80%;
  margin: 0 auto; /* 水平居中 */
  padding: 2%;
}
  1. 响应式设计:
.box {
  width: 100%;
  max-width: 1200px;
  padding: 20px;
}

CSS动画

CSS 动画可以为 HTML 元素创建平滑的视觉效果,无需使用 JavaScript。CSS 提供了两种主要的动画技术:过渡(Transitions)和关键帧动画(Animations)。

CSS 过渡(Transitions)

过渡用于在元素从一个状态变为另一个状态时添加动画效果。

基本语法

.element {
  transition: property duration timing-function delay;
}

属性说明

属性说明示例值
transition-property指定要过渡的属性allwidthopacity
transition-duration过渡持续时间1s200ms
transition-timing-function过渡速度曲线easelinearease-in
transition-delay过渡开始前的延迟时间0.5s100ms

示例

.box {
  width: 100px;
  height: 100px;
  background: red;
  transition: width 1s ease-in-out;
}

.box:hover {
  width: 200px;
}

多个属性过渡

.box {
  transition: width 1s ease, height 0.5s linear, background 2s;
}

过渡速度曲线(timing-function)

  • ease - 默认值,慢快慢(相当于 cubic-bezier(0.25, 0.1, 0.25, 1)
  • linear - 匀速(cubic-bezier(0, 0, 1, 1)
  • ease-in - 慢开始(cubic-bezier(0.42, 0, 1, 1)
  • ease-out - 慢结束(cubic-bezier(0, 0, 0.58, 1)
  • ease-in-out - 慢开始和结束(cubic-bezier(0.42, 0, 0.58, 1)
  • cubic-bezier(n,n,n,n) - 自定义贝塞尔曲线
  • steps(n, start|end) - 分步动画

CSS 关键帧动画(Animations)

关键帧动画提供了比过渡更复杂的控制能力,可以定义多个关键帧和更复杂的动画序列。

基本语法

  1. 定义关键帧:
@keyframes animation-name {
  from { /* 起始状态 */ }
  to { /* 结束状态 */ }
  
  /* 或使用百分比 */
  0% { /* 动画开始时 */ }
  50% { /* 动画进行到一半时 */ }
  100% { /* 动画结束时 */ }
}
  1. 应用动画:
.element {
  animation: name duration timing-function delay iteration-count direction fill-mode play-state;
}

属性说明

属性说明示例值
animation-name关键帧动画名称slidefade
animation-duration动画持续时间1s200ms
animation-timing-function动画速度曲线easelinear
animation-delay动画开始前的延迟0.5s100ms
animation-iteration-count动画播放次数1infinite
animation-direction动画播放方向normalreversealternate
animation-fill-mode动画前后如何应用样式noneforwardsbackwardsboth
animation-play-state动画播放状态runningpaused

示例

@keyframes slide {
  from { transform: translateX(0); }
  to { transform: translateX(100px); }
}

.box {
  animation: slide 2s ease-in-out infinite alternate;
}

复杂关键帧示例

@keyframes bounce {
  0% { transform: translateY(0); }
  20% { transform: translateY(-30px); }
  40% { transform: translateY(0); }
  60% { transform: translateY(-15px); }
  80% { transform: translateY(0); }
  100% { transform: translateY(0); }
}

.ball {
  animation: bounce 1s ease infinite;
}

常用动画属性

CSS 中常用于动画的属性包括:

  1. 变换(Transform)

    • translate() - 移动
    • rotate() - 旋转
    • scale() - 缩放
    • skew() - 倾斜
    • matrix() - 矩阵变换
  2. 透明度(Opacity)

    • opacity: 0-1 - 元素透明度
  3. 颜色属性

    • colorbackground-colorborder-color 等
  4. 尺寸属性

    • widthheightmax-height 等
  5. 布局属性

    • marginpaddingtopleft 等

性能优化建议

  1. 优先使用 transform 和 opacity

    • 这些属性可以由GPU加速,性能更好
    • 避免动画中使用 widthheightmargin 等会导致重排的属性
  2. 使用 will-change 属性

.element {
  will-change: transform, opacity;
}

提前告知浏览器哪些属性会变化,但不要过度使用

  1. 减少动画元素数量

    • 同时动画的元素越多,性能消耗越大
  2. 适当使用硬件加速

.element {
  transform: translateZ(0);
}
  1. 合理设置动画持续时间

    • 通常200-500ms的动画效果最佳

实际应用示例

1. 淡入淡出效果

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.fade-in {
  animation: fadeIn 0.5s ease-in forwards;
}

2. 旋转加载动画

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

.loader {
  animation: spin 1s linear infinite;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  width: 30px;
  height: 30px;
}

3. 悬停放大效果

.card {
  transition: transform 0.3s ease;
}

.card:hover {
  transform: scale(1.05);
}

4. 弹跳按钮

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

.button:active {
  animation: bounce 0.3s;
}

浏览器兼容性

大多数现代浏览器都支持CSS动画,但需要注意:

  • 添加浏览器前缀以确保兼容旧版浏览器:
@-webkit-keyframes example { /* Safari/Chrome */ }
@-moz-keyframes example { /* Firefox */ }
@-o-keyframes example { /* Opera */ }
@keyframes example { /* 标准语法 */ }
  • 使用工具如Autoprefixer自动添加前缀

浮动/定位/布局

浮动

浮动是 CSS 中一种传统的布局方式,最初设计用于实现文字环绕图片的效果,后来被广泛用于网页布局。

浮动的基本概念

  1. 浮动属性
.float-element {
  float: left;   /* 向左浮动 */
  float: right;  /* 向右浮动 */
  float: none;   /* 不浮动(默认值) */
}
  1. 浮动元素的特点
  • 脱离普通文档流(但仍在文档流中占据位置)
  • 向左或向右移动,直到碰到包含框或另一个浮动元素
  • 后面的行内内容会环绕浮动元素
  • 宽度默认为内容宽度(而非父元素的100%)

浮动的使用场景

  1. 文字环绕图片
<img src="image.jpg" class="float-left">
<p>这里是围绕图片的文字内容...</p>

.float-left {
  float: left;
  margin-right: 15px;
  margin-bottom: 15px;
}
  1. 创建多栏布局
<div class="column left">左侧内容</div>
<div class="column right">右侧内容</div>

.column {
  width: 50%;
  box-sizing: border-box;
  padding: 20px;
}

.left {
  float: left;
  background: #f0f0f0;
}

.right {
  float: right;
  background: #e0e0e0;
}

清除浮动(Clearing Floats)

浮动元素会导致父元素高度塌陷(无法自动撑开),需要清除浮动。

  1. 清除浮动的方法
  • 空div清除法
<div class="clearfix"></div>

.clearfix {
  clear: both;
}
  • 父元素使用 overflow
.parent {
  overflow: hidden; /* 或 auto */
}
  • 使用伪元素(推荐)
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
  • 现代布局替代方案
.parent {
  display: flow-root; /* 创建BFC */
}
  1. clear 属性
.clear-left {
  clear: left;   /* 清除左浮动 */
}

.clear-right {
  clear: right;  /* 清除右浮动 */
}

.clear-both {
  clear: both;   /* 清除左右浮动 */
}

浮动的常见问题与解决方案

  1. 高度塌陷问题

现象:父元素无法自动包含浮动子元素的高度

解决方案

  • 使用上述清除浮动的方法
  • 父元素设置固定高度(不推荐,缺乏灵活性)
  1. 外边距重叠问题

现象:浮动元素与非浮动元素之间的垂直 margin 可能不会正常表现

解决方案

  • 使用 padding 替代 margin
  • 添加透明边框 border: 1px solid transparent
  1. 浮动元素超出容器

现象:浮动元素可能超出其父容器

解决方案

  • 父容器添加 overflow: hidden
  • 使用 clearfix 技术

浮动布局的局限性

  1. 布局不够灵活:难以实现复杂的响应式布局
  2. 代码维护困难:需要大量清除浮动的代码
  3. 垂直居中困难:浮动元素难以实现垂直居中
  4. 现代替代方案:Flexbox 和 Grid 布局更适合现代网页

浮动与Flexbox/Grid的对比

特性浮动FlexboxGrid
布局方向水平任意方向二维
对齐控制有限强大强大
响应式困难容易容易
清除浮动需要不需要不需要
浏览器支持所有IE10+IE10+(部分)

实际应用示例

  1. 导航菜单
<nav class="menu">
  <ul>
    <li><a href="#">首页</a></li>
    <li><a href="#">产品</a></li>
    <li><a href="#">服务</a></li>
    <li><a href="#">关于</a></li>
  </ul>
</nav>

.menu ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  float: left;
  margin-right: 20px;
}

.menu::after {
  content: "";
  display: table;
  clear: both;
}
  1. 图文混排
<article class="post">
  <img src="thumbnail.jpg" class="post-thumb">
  <div class="post-content">
    <h2>文章标题</h2>
    <p>文章内容...</p>
  </div>
</article>

.post-thumb {
  float: left;
  margin-right: 20px;
  width: 200px;
}

.post::after {
  content: "";
  display: table;
  clear: both;
}

最佳实践建议

  1. 尽量使用现代布局:优先考虑 Flexbox 或 Grid 布局
  2. 合理使用清除浮动:推荐使用伪元素方法
  3. 注意浏览器兼容性:浮动在旧浏览器中表现良好
  4. 避免过度嵌套浮动:会增加布局复杂度
  5. 结合 BFC 使用:理解浮动与块格式化上下文的关系

定位

CSS 定位系统允许你精确控制元素在页面上的位置,是网页布局的核心技术之一。

定位类型

CSS 提供了 5 种定位方式:

  1. 静态定位 (static) - 默认值
position: static;
  • 元素遵循正常文档流
  • top、right、bottom、left 和 z-index 属性无效
  1. 相对定位 (relative)
position: relative;
top: 10px;
left: 20px;
  • 元素相对于自身原始位置进行偏移
  • 保留原始空间,不影响其他元素布局
  • 常用于微调元素位置或作为绝对定位的参照容器
  1. 绝对定位 (absolute)
position: absolute;
top: 0;
right: 0;
  • 元素脱离文档流,不占据空间
  • 相对于最近的非 static 定位祖先元素定位
  • 如果没有符合条件的祖先,则相对于初始包含块(通常是视口)
  • 常用于创建弹出层、下拉菜单等
  1. 固定定位 (fixed)
position: fixed;
bottom: 20px;
right: 20px;
  • 元素脱离文档流,不占据空间
  • 相对于浏览器视口定位
  • 不随页面滚动而移动
  • 常用于固定导航栏、返回顶部按钮等
  1. 粘性定位 (sticky)
position: sticky;
top: 0;
  • 元素根据滚动位置在 relative 和 fixed 之间切换
  • 在阈值范围内表现为 fixed,否则表现为 relative
  • 必须指定至少一个阈值(top/right/bottom/left)
  • 常用于吸顶导航、表头固定等效果

定位属性

定位元素可使用以下属性调整位置:

属性描述示例
top上边缘偏移top: 10px
right右边缘偏移right: 5%
bottom下边缘偏移bottom: 0
left左边缘偏移left: 20px
z-index堆叠顺序z-index: 100

z-index 堆叠上下文

  • 控制定位元素的垂直堆叠顺序
  • 值越大,元素越靠前(可为正/负整数)
  • 仅对定位元素(position非static)有效
  • 相同z-index时,后出现的元素在上层
.modal {
  position: absolute;
  z-index: 1000;
}

实际应用示例

  1. 居中定位(经典方法)
.center-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  height: 200px;
}
  1. 固定页脚
.footer {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: #333;
  color: white;
}
  1. 粘性表头
.table-header {
  position: sticky;
  top: 0;
  background: white;
  z-index: 10;
}
  1. 下拉菜单
.menu {
  position: relative;
}
.dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  display: none;
}
.menu:hover .dropdown {
  display: block;
}

定位与文档流

定位类型是否脱离文档流定位基准
static正常流
relative否(保留空间)自身位置
absolute最近非static祖先
fixed视口
sticky否(阈值内脱离)最近滚动容器

常见问题与解决方案

  1. 绝对定位元素超出容器

问题:绝对定位子元素可能被父容器裁剪

解决

.parent {
  position: relative;
  overflow: visible; /* 默认值 */
}
  1. z-index 不生效

原因

  • 元素未设置定位(position非static)
  • 被父元素的z-index上下文限制

解决

.element {
  position: relative; /* 或其他非static值 */
  z-index: 1;
}
  1. 粘性定位无效

原因

  • 父元素有overflow:hidden/scroll设置
  • 未指定阈值(top/right等)

解决

.sticky-element {
  position: sticky;
  top: 0; /* 必须指定 */
}
.parent {
  overflow: visible; /* 确保不是hidden/scroll */
}

最佳实践

  1. 合理选择定位类型

    • 微调位置 → relative
    • 弹出层/悬浮元素 → absolute
    • 固定元素 → fixed
    • 滚动吸附 → sticky
  2. 建立定位上下文

.parent {
  position: relative; /* 创建定位上下文 */
}
  1. 避免过度使用绝对定位

    • 可能导致布局脆弱,难以维护
    • 现代布局优先考虑Flexbox/Grid
  2. 处理移动端fixed定位

    • iOS Safari对fixed支持有限,考虑使用absolute+JS
  3. 性能考虑

    • fixed和sticky定位可能影响滚动性能
    • 大量定位元素会增加渲染负担

布局

CSS 布局是前端开发的核心技能,现代 CSS 提供了多种布局技术,从传统的浮动到现代的 Flexbox 和 Grid 布局系统。

传统布局方法

  1. 基于浮动的布局 (Float Layout)
.column {
  float: left;
  width: 33.33%;
  box-sizing: border-box;
  padding: 15px;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}

特点

  • 早期网页主要布局方式
  • 需要清除浮动
  • 实现复杂布局困难
  1. 基于定位的布局 (Position Layout)
.header {
  position: fixed;
  top: 0;
  width: 100%;
}

.sidebar {
  position: absolute;
  left: 0;
  width: 200px;
}

.main {
  margin-left: 200px;
}

特点

  • 适合特定元素定位
  • 脱离文档流需谨慎使用
  • 不适合整体页面布局

现代布局系统

1. Flexbox 弹性盒子布局

基本结构

.container {
  display: flex;
  flex-direction: row; /* 主轴方向: row | row-reverse | column | column-reverse */
  flex-wrap: nowrap; /* nowrap | wrap | wrap-reverse */
  justify-content: flex-start; /* 主轴对齐 */
  align-items: stretch; /* 交叉轴对齐 */
  gap: 10px; /* 项目间距 */
}

.item {
  flex: 1; /* flex-grow | flex-shrink | flex-basis */
  align-self: auto; /* 单个项目对齐 */
}

典型应用

  1. 水平垂直居中
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
  1. 等宽卡片布局
.card-container {
  display: flex;
  flex-wrap: wrap;
}

.card {
  flex: 1 1 300px;
  margin: 10px;
}
2. CSS Grid 网格布局

基本结构

.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr; /* 列定义 */
  grid-template-rows: 100px auto 50px; /* 行定义 */
  gap: 15px; /* 网格间距 */
  grid-template-areas: 
    "header header header"
    "sidebar main aside"
    "footer footer footer";
}

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

典型应用

  1. 经典12列网格
.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 20px;
}

.col-4 {
  grid-column: span 4;
}
  1. 响应式网格
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}

多列布局 (Multi-column)

.article {
  column-count: 3;
  column-gap: 30px;
  column-rule: 1px solid #ddd;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .article {
    column-count: 2;
  }
}

布局技术对比

特性FloatPositionFlexboxGrid
维度一维二维一维二维
文档流半脱离完全脱离正常正常
对齐控制有限强大强大
响应式困难困难容易容易
适用场景文字环绕特定定位组件布局整体布局

实用布局解决方案

  1. 圣杯布局 (Holy Grail)
.container {
  display: grid;
  grid-template: 
    "header header header" 80px
    "nav main aside" 1fr
    "footer footer footer" 60px
    / 200px 1fr 200px;
  min-height: 100vh;
}
  1. 粘性页脚 (Sticky Footer)
body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.main {
  flex: 1;
}
  1. 瀑布流布局 (Masonry)
.masonry {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-auto-rows: 10px;
}

.item {
  grid-row-end: span var(--row-span);
}

响应式布局策略

  1. 媒体查询断点
/* 移动优先 */
.container {
  padding: 10px;
}

@media (min-width: 768px) {
  .container {
    max-width: 720px;
    margin: 0 auto;
  }
}
  1. 视口单位
.hero {
  height: 100vh;
  font-size: calc(1rem + 1vw);
}
  1. 弹性布局
.flex-responsive {
  display: flex;
  flex-wrap: wrap;
}

.flex-responsive > * {
  flex: 1 1 300px;
}

布局最佳实践

  1. 移动优先:从小屏幕开始设计,逐步增强

  2. 渐进增强:确保基础布局在所有设备可用

  3. 合理选择技术

    • 整体布局 → Grid
    • 组件布局 → Flexbox
    • 传统维护 → Float
  4. 性能考虑

    • 减少布局重排
    • 避免深层嵌套
  5. 可维护性

    • 使用命名网格区域
    • 添加布局注释
    • 保持代码一致性

未来布局趋势

  1. 子网格 (subgrid)
.grid {
  display: grid;
  grid-template-columns: subgrid;
}
  1. 容器查询
@container (min-width: 500px) {
  .card {
    display: flex;
  }
}
  1. 层叠上下文 (Layer)
@layer layout {
  .grid {
    display: grid;
  }
}