1.静态定位
静态定位:position取值为static,他是HTML文档元素的默认值,不受top、bottom、left、right属性影响,并且不能进行z-index分层,元素在这次的文档流中。
<style>
div{
background-color: gray;
width: 400px;
height: 300px;
top: 400px;
left: 400px;
}
</style>
<body>
<div>
</div>
</body>
2.相对定位
相对定位:当position取值为relative时,该元素为相对定位,相对自身位置定位,不会脱离文档流,可以使用z-index进行分层。它可以根据文档正常流动偏移相对于它本身top、bottom、right和left的值,偏移量不会影响其他元素的位置。
<style>
.a1{
background-color: gray;
width: 400px;
height: 300px;
top: 400px;
left: 400px;
}
.a2{
background-color: rgb(188, 231, 86);
width: 400px;
height: 300px;
top: 100px;
left: 100px;
position: relative;
}
</style>
<body>
<div class="a1">
</div>
<div class="a2">
</div>
</body>
3.绝对定位
绝对定位:当position取值为absolute时,是绝对定位,脱离文档流的布局,后面的元素会填补它空下来的位置,它的起始位置为最近的position值而不是static的父元素,若没有则是以HTML为准,由top、bottom、left、right确定最终位置,可以使用z-index进行分层。
<style>
.a1{
background-color: gray;
width: 400px;
height: 300px;
top: 400px;
left: 400px;
}
.a2{
background-color: rgb(188, 231, 86);
width: 600px;
height: 200px;
top: 100px;
left: 100px;
position:absolute;
}
</style>
<body>
<div class="a1">
</div>
<div class="a2">
</div>
</body>
以下是图一为相对定位,图二为绝对定位情况
<style>
.a1{
background-color: gray;
width: 400px;
height: 300px;
top: 50px;
left: 50px;
position: relative;
}
.a2{
background-color: rgb(188, 231, 86);
width: 600px;
height: 200px;
top: 100px;
left: 100px;
position:absolute;
}
</style>
<body>
<div class="a1">
</div>
<div class="a2">
</div>
</body>
以下是父元素是相对定位,子元素是绝对定位的情况
<style>
.a1{
background-color: gray;
width: 400px;
height: 300px;
top: 50px;
left: 50px;
position: relative;
}
.a2{
background-color: rgb(188, 231, 86);
width: 600px;
height: 200px;
top: 100px;
left: 100px;
position:absolute;
}
</style>
<body>
<div class="a1">
<div class="a2">
</div>
</div>
4.固定定位
固定定位:当position的取值为fixed时,该元素为固定定位,脱离文档流,它的起始位置相对于视图是固定位置不随滚动条的滑动而滚动。一般像导航栏大多数会使用固定定位。
5.粘性定位
粘性定位:当position取值为sticky时该元素为粘性定位,它会脱离文档流,会在文档流中预留该元素的物理空间;它的相对偏移是相对于父标签而言,设置top等值只会在父标签中sticky。