position定位的认识

首先

position有五个取值:static(静态)、relative、absolute、fixed、sticky

1、static:默认的定位方式,应用该定位的元素在文案流内。此时 toprightbottomleft 和 z-index 属性无效。

2、relative:应用该定位的元素在文档流内,他会占据原有的位置,从原有的位置进行偏移。

3、absolute:应用该定位的元素会脱离文档流,他会自动向上级寻找定位的元素,当找到有定位的元素,就会以那个元素来进行相对定位,如果他的父级或祖先级没有定位的 元素,就以body元素进行绝对定位,此定位会跟着页面滚动而滚动。

4、fixed:应用该定位的元素会脱离文档流,此元素相对于屏幕视口的位置来定位,当页面滚动时,此元素不会随着页面滚动而滚动

5、sticky:应用该定位的元素在文档流内,此元素会在文档的正常位置,此元素在它父元素的容器内是类似fixed定位,当他与后续的块级元素粘粘时,他会被顶走

下面是代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .box div{
        width: 200px;
        height: 200px;
        background-color: aquamarine;
        margin-right: 30px;
        display: inline-block;
        text-align: center;
        font-size: 30px;
        line-height: 200px;
    }
    .two{
        position: relative;
        left: 20px;
        top: 20px;
    }
    .box .three{
        position: absolute;
        left: 100px;
        background-color:rgb(194, 173, 176);
        z-index: 77;
        opacity: .6;
    }
    .box2{
        height: 600px;
        position: relative;
    }
    .a{
        position: sticky;
        height: 100px;
        width: 100px;
        top: 100px;
        background-color: rgb(182, 189, 186);
        margin-bottom: 100px;
    }
    .b{
        position: sticky;
        height: 100px;
        width: 100px;
        top: 50px;
        opacity: .8;
        background-color: rgb(118, 219, 175);
    }
    .box3{
        height: 1200px;
        background-color: aquamarine;
    }
</style>
<body>
    <div class="box">
        <div class="one">one</div>
        <div class="two">two</div>
        <div class="three">three</div>
        <div class="four">four</div>
    </div>
    <div class="box2">
        <div class="a">absol</div>
        <div class="b"></div>
    </div>
    <div class="box3"></div>
</body>
</html>
原文地址:https://www.cnblogs.com/curtain473/p/9690778.html