问:position: fixed什么时候会失效?

position: fixed什么时候会失效?

我们知道,设置了position: fixed固定定位属性的元素会脱离文档流,达到“超然脱俗”的境界。
也就是说此时给这种元素设置top, left, right, bottom等属性是根据浏览器窗口定位的,与其上级元素的位置无关。
但是有一种情况例外:
若是设置了position: fixed属性的元素,它的上级元素设置了transform属性则会导致固定定位属性失效。
无论你的transform设置的是什么属性都会影响到position: fixed
看下面的案例1:

<style>
    .father {
        width: 300px;
        height: 300px;
        background: yellow;
        transform: translate(100px); 
        /* transform: scale(0.5); */
        /* transform: rotate(-45deg); */
    }
    .son {
        width: 100px;
        height: 100px;
        background: red;
        position: fixed;
        top: 400px;
    }
</style>
<body>
<div class="father">
   <div class="son"></div>
</div>
</body>

给父级加上了transform属性之后就会影响子级的固定定位了。如下图:

7190596-38462e3ec67bd654.png
没加transform.png

7190596-5bcc360baa0d652b.png
加了transform.png

其实不仅仅是给父级加transform属性会失效,只要上级存在transform属性都会导致position: fixed失效。

案例2:

<style>
    .content{
        transform: translate(100px);
    }
    .father {
        width: 300px;
        height: 300px;
        background: yellow;
    }
    .son {
        width: 100px;
        height: 100px;
        background: red;
        position: fixed;
        top: 400px;
    }
</style>
<body>
    <div class="content">
        <div class="father">
            <div class="son"></div>
        </div>
    </div>
</body>

上面的案例也会影响position: fixed属性。

猜你喜欢

转载自blog.csdn.net/weixin_34399060/article/details/86782115