一、相对定位
- 写法
position:relative;
left:10px;
- 特点
- 不会脱离文档流
- 定位原素显示层级比普通原素高,不同定位原素显示层级相同,默认规则是:定位原素会覆盖普通原素上,如果两个定位原素位置冲突,后写的定位原素会覆盖普通原素上
- left不能和right同时用,top和bottom不能同时用
- 可以同时设置浮动,不推荐
- 可以同时设置margin,不推荐
二、绝对定位
- 写法
position:absolute;
- 包含块
- 没有脱离文档流的原素,父原素就是包含块
- 脱离文档流的原素,第一个开启定位的祖先原素,就是它的包含块,如果没有,包含块是整个页面
- 特点
- 脱离文档流
- left和right不能同用,top和bottom不能同用
- 同时设置浮动会失效,以绝对定位为主
- 可以同时设置margin,不推荐
- 无论什么原素,设置绝对定位,都变成定位原素
- 定位原素
默认宽高由内容撑开,可以设置宽高
三、固定定位
- 写法
position:fixed;
- 视口
程序在浏览器运行整个界面 - 特点
- 脱离文档流
- left和right不能同用,top和bottom不能同用
- 同时设置浮动会失效,以固定定位为主
- 可以同时设置margin,不推荐
- 无论什么原素,设置固定定位,都变成定位原素
四、粘性定位
- 写法
posotion:sticky;
- 特点
- 不脱离文档流
- top值常用
- 可以同时设置margin,不推荐
- 可以同时设置浮动,不推荐
五、定位的层级
- 定位原素的层级比普通原素高,不同定位原素层级相同
- 定位原素重叠,默认后者覆盖前者
- 可以通过
z-index
调整显示层级 - z-index值是数字,没有单位,值越大,显示层级越高
- 只有定位原素z-index才有效
- z-index值大的没有覆盖z-index值小的,可能是包含块设置z-index值过小
六、特殊应用(只适应于绝对定位和固定定位)
- 让定位原素充满包含块
<style type="text/less">
.position-full {
width:200px;
height:200px;
position:relative;
div:first-child {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
background-color:red;
}
}
</style>
<div class="position-full">
<div></div>
</div>
- 让定位原素在包含块水平垂直居中
<style type="text/less">
.position-center {
width:200px;
height:200px;
background-color:black;
position:relative;
div:first-child {
position:absolute;
width:100px;
height:100px;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
background-color:red;
}
}
</style>
<div class="position-center">
<div></div>
</div>