css定位

CSS 定位

基本概念

  • 定位布局可以实现更精确的元素位置控制。
  • 但相比普通文档流和弹性布局,定位的灵活性通常更差。

常见定位方式

相对定位 relative

  • 相对于元素原本在文档流中的位置进行定位。
  • 元素仍然占据原来的文档流位置。
1
2
3
position: relative;
left: 20px;
top: 10px;

绝对定位 absolute

  • 相对于最近的已定位祖先元素进行定位。
  • 如果没有已定位祖先,一般相对于浏览器页面进行定位。
  • 脱离文档流,不再占据原来的位置。
1
2
position: absolute;
left: 120px;

固定定位 fixed

  • 相对于浏览器窗口进行定位。
  • 脱离文档流。
  • 固定在屏幕中的某个位置,不会随着页面滚动而移动。
1
2
3
position: fixed;
right: 100px;
top: 20px;

课堂完整示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>定位</title>
<style>
.box1{
height: 350px;
background-color: turquoise;
}
.box-normal{
width: 100px;
height: 100px;
background-color: red;
}
.box-relative{
width: 100px;
height: 100px;
background-color: blue;
position: relative;
left: 20px;
top: 10px;
right: 20px;
bottom: 10px;
}
.box2{
height: 350px;
background-color: yellow;
margin-bottom: 300px;
}
.box-absolute{
width: 100px;
height: 100px;
background-color: green;
position: absolute;
left: 120px;
}
.box-fixed{
width: 100px;
height: 100px;
background-color: pink;
position: fixed;
right: 100px;
top: 20px;
}
</style>
</head>
<body>
<h1>相对定位</h1>
<div class="box1">
<div class="box-normal"></div>
<div class="box-relative"></div>
<div class="box-normal"></div>
</div>

<h1>绝对定位</h1>
<div class="box2">
<div class="box-normal"></div>
<div class="box-absolute"></div>
<div class="box-normal"></div>
</div>

<h1>固定定位</h1>
<div class="box-fixed">
</div>
</body>
</html>

知识点总结

  • 相对定位不脱离文档流。
  • 绝对定位和固定定位都会脱离文档流。
  • 绝对定位常依赖最近的已定位祖先元素。
  • 固定定位常用于返回顶部、悬浮按钮、吸附工具栏等场景。

复习表达

CSS 定位主要包括相对定位、绝对定位和固定定位。相对定位是相对于元素原本位置进行偏移,但仍然保留原来的文档流位置;绝对定位是相对于最近的已定位祖先元素进行定位,并且脱离文档流;固定定位是相对于浏览器窗口定位,也脱离文档流,常用于页面中的悬浮元素。