CSS定位详解

CSS position

CSS position属性用于指定一个元素在文档中的定位方式,定位分为静态定位,相对定位,绝对定位,固定定位、粘性定位这五种其中top、right、bottom、left和z-index属性则决定了该元素的最终位置。

静态定位(static)

一般的标签元素不加任何定位属性都属于静态定位,在页面的最底层属于标准流。

  1. 对边偏移无效。
  2. 可以用来清除定位
  3. left、top、right、bottom 均不可使用
  4. 占空间

相对定位(relative)

  1. 相对定位可以通过边偏移来移动位置,相对本身原来的位置做的定位改变,原来的位置继续占有。
  2. top、right、bottom、left 均可设置
  3. 相对于页面做的改变
  4. 如果说浮动是让多个块级元素一行显示,那么定位的价值是让我们的盒子移动到我们想要的位置上去。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<head>
<style type="text/css">
.box {
background: red;
width: 100px;
height: 100px;
float: left;
margin: 5px;
}
.two {
position: relative;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="box" >One</div>
<div class="box two" >Two</div>
<div class="box" >Three</div>
<div class="box">Four</div>
</body>

绝对定位(absolute)

1,当父级没有设置除静态定位(static)意外的定位,那么将往上级找定位,如果上级都没定那么将根据根(html)标签做定位
2, 当父级设置除静态定位(static)意外的定位,那么将按照父级做改变
3,top、right、bottom、left 均可设置
4,相对于页面做的改变
5,不占空间

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

<!--

子绝父相
子绝对定位,父亲相对定位。
相对定位 占有位置 不脱标
绝对定位 不占有位置 脱标
-->

<head>
<style type="text/css">
.box {
background: red;
width: 100px;
height: 100px;
float: left;
margin: 5px;
}
.two {
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="box" >One</div>
<div class="box two" >Two</div>
<div class="box" >Three</div>
<div class="box">Four</div>
</body>

固定定位(fixed)

  1. 固定定位与绝对定位类似,但它是相对于浏览器窗口定位,并且不会随着滚动条进行滚动。
  2. 不占空间
  3. top、right、bottom、left 均可设置
  4. 不受祖先元素影响

粘性定位(sticky)

  1. 相对于父级占空间
  2. top、right、bottom、left 均可设置
  3. 粘性定位可以被认为是相对定位和固定定位的混合。元素在跨越特定阈值前为相对定位,之后为固定定位。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div class="sticky">我是粘性定位!</div>

<div style="padding-bottom:2000px">
<p>滚动我</p>
<p>来回滚动我</p>
<p>滚动我</p>
<p>来回滚动我</p>
<p>滚动我</p>
<p>来回滚动我</p>
</div>

<style>
div.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
padding: 5px;
background-color: #cae8ca;
border: 2px solid #4CAF50;
}
</style>

##总结

定位模式 是否脱标 移动位置 是否常用
static 静态定位 不能使用边偏移 很少
relative 相对定位 否 (占有位置) 相对于自身位置移动 基本单独使用
absolute绝对定位 是(不占有位置) 带有定位的父级 要和定位父级元素搭配使用
fixed 固定定位 是(不占有位置) 浏览器可视区 单独使用,不需要父级
sticky 粘性定位 否 (占有位置) 浏览器可视区 当前阶段少