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

我们知道,设置了position: fixed固定定位属性的元素会脱离文档流,达到“超然脱俗”的境界。 也就是说此时给这种元素设置top, left, right, bottom等属性是根据浏览器窗口定位的,与其上级元素的位置无关。

但是有一种情况例外:

若是设置了position: fixed属性的元素,它的上级元素设置了transform属性则会导致固定定位属性失效。 无论你的transform设置的是什么属性都会影响到position: fixed

注意,这个特性表现,目前只在Chrome浏览器/FireFox浏览器下有,IE浏览器,包括IE11, fixed还是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属性之后就会影响子级的固定定位了。如下图:

其实不仅仅是给父级加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属性。

具体原理可以看一下张大大的这篇文章:https://www.zhangxinxu.com/wordpress/2015/05/css3-transform-affect/

阅读全文