1. 定义
相对定位: 是相对于它本身所在的文档流的位置进行定位,不会脱离文档流,定位前的位置依然保留。
绝对定位: 相对于它最近的设置过position某些属性(如:relative、obsolute、fixed、sticky )的祖先结点来进行定位。如果祖先节点中没有设置,默认相对于body定位。会脱离文档流,文档中不会保留其定位前的位置。
2.解释
我们来介绍三个常用的属性relative(相对定位)、absolute(绝对定位)、fixed(固定定位,也是绝对定位),来区分相对定位和绝对定位。
<style>
html{
background: #000;
}
.wrap{
width: 600px;
height: 600px;
background: #aaa;
}
.test{
width: 50px;
height: 50px;
background: green;
}
.item{
width: 200px;
height: 200px;
background: red;
}
</style>
<body>
<div class="wrap">
<div class="item"> 123 </div>
<div class="test"></div>
</div>
</body>
我写了一个简单的html样式,页面的效果如下: 整个页面背景色为黑色,有一个背景为灰色的盒子wrap,里面有一个背景为红色的大盒子item和一个背景为绿色的小盒子test
现在就分别介绍各个定位的功能:(我们只对红色的盒子item进行操作)
1. relative
<style>{
.item{
width: 200px;
height: 200px;
background: red;
/* 添加相对定位属性 */
position: relative;
left: 100px;
}
</style>
给test盒子加上relative属性,在相对于自己的文档流距离左边100px,页面效果如下: 此时绿色的盒子并没有上去,说明红色盒子没有脱离文档流,还占据一定空间。
2.absolute
<style>{
.item{
width: 200px;
height: 200px;
background: red;
/* 添加绝对定位属性 */
position: absolute;
left: 100px;
}
</style>
现在我们把属性换成absolute,你会发现,这个时候,绿色的盒子却上去了,说明这个属性会使红色的盒子脱离文档流,并没有占据一定的空间。
3.fixed
<style>{
.item{
width: 200px;
height: 200px;
background: red;
/* 添加固定定位属性 */
position: fixed;
right:0;
}
</style>
此时,可以明显看出,该红色的盒子已经跑出灰色的盒子了,到外面去了,而且绿色的盒子也上去了,说明脱离了文档流。
因为父容器并没有加position的任何属性,所以相对定位都是相对于body定位的,可能你会有这个疑问,此时给绿色的盒子也加上和红色的盒子一样的属性,结果也是一样的,无法说明fixed属性就是相对于window定位的,下面我们就给父容器wrap加上relative属性,让它的子容器item和test都相对于它来定位,我们来看看absolute和fixed的本质区别:
<style>
.wrap{
width: 600px;
height: 600px;
background: #aaa;
position: relative;
}
.test{
width: 50px;
height: 50px;
background: green;
position: absolute;
right: 0;
}
.item{
width: 200px;
height: 200px;
background: red;
position: fixed;
right: 0;
}
</style>
这样一对比就有说服力了,因为item和test的父容器都是wrap。加了absolute属性的test是相对于wrap定位的,而加了fixed属性的item则是相对于window定位的,不管它的父容器有没有相对属性。
3.小结
position中relative filed absolute 的区别:
- relative 相对定位,相对于自己的文档流的位置定位,不会脱离文档流
- absolute 绝对定位,相对于具有relative、obsolute、fixed、sticky 的最近的父容器来定位,会脱离文档流
- fixed 绝对定位(通常叫做:固定定位),相对于window位置定位,会脱离文档流