1、static:静态定位,默认,相当于没设置,top、right、bottom、left属性(以下简称TRBL)和z-index属性不生效
2、fixed:固定定位,相对于浏览器窗口来定位,TRBL属性和z-index属性有效
3、relative:相对定位,相对于直接父级来定位,TRBL属性和z-index属性有效
4、absolute:绝对定位,相对于同类父级来定位,即向上查找紧邻的父级position属性为fixed/relative/absolute的元素来定位,TRBL属性和z-index属性有效
示意图:
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position</title>
</head>
<style>
.div {
width: 300px;
height: 300px;
background-color: gray;
}
.middle {
width: 230px;
height: 120px;
margin: 10px;
background-color: lightblue;
border: 1px solid white;
}
.static {
width: 90px;
height: 90px;
top: 20px;
right: 0px;
bottom: 0px;
left: 30px;
background-color: yellow;
border: 1px solid white;
position: static
}
.relative {
width: 200px;
height: 120px;
top: 20px;
right: 0px;
bottom: 0px;
left: 30px;
background-color: green;
border: 1px solid white;
position: relative
}
.absolute {
width: 180px;
height: 110px;
top: 20px;
right: 0px;
bottom: 0px;
left: 30px;
background-color: coral;
border: 1px solid white;
position: absolute
}
.fixed {
width: 160px;
height: 100px;
top: 230px;
right: 0px;
bottom: 0px;
left: 330px;
background-color: blue;
border: 1px solid white;
position: fixed
}
</style>
<body>
<div class="div">
<div class="static">
div1/static
</div>
</div>
<br>
<div class="div">
<div class="relative">
div2/relative
<div class="middle">
middle
<div class="absolute">
middle/absolute
</div>
</div>
</div>
</div>
<br>
<div class="div">
<div class="absolute">
div3/absolute
<div class="absolute">
absolute/absolute
</div>
</div>
</div>
<br>
<div class="div">
<div class="fixed">
div4/fixed
<div class="absolute">
fixed/absolute
</div>
</div>
</div>
</body>
</html>
参考资料