position:fixed实现相对于父级定位

position:fixed是对于浏览器窗口定位的,要实现相当于父元素定位,可以这样:

不设置fixed元素的top,bottom,left,right,只设置margin来实现。

这种方法本质上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>
    .wrapper{
     
     
        position: relative;
        height: 1000px;
        width: 600px;
        margin: 20px auto;
        background: pink;
    }
    .box1,.box2{
     
     
        height: 100px;
        width: 100%;
        background: #f39bdc;
    }
    .box2{
     
     
        background: #8abe8a;
    }
    .click{
     
     
        position: fixed;
        margin-left: 599px;
        width: 60px;
        height: 20px;
        text-align: center;
        border: 1px solid blueviolet;
    }
</style>
<body>
    <div class="wrapper">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
        <div class="click">点击</div>
    </div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/callmeCassie/article/details/102760097