position:fixed通常情况下是相对于窗口定位的,但是有一种情况,position:fixed是相对于祖先元素定位,而此时的定位层级(z-index)也是相对于祖先元素的。
这种情况就是让祖先元素发生变换,也就是transfrom属性发生改变。
实例:
<div class='parent'>
<div class='child'>我固定了吗?</div>
</div>
<div class='parentSibling'>
</div>
对应的css样式
.parent{
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
background: #6699FF;
animation: move 4s cubic-bezier(0.4,0,0.6,1) infinite;
position:absolute;
left:0px;
z-index:100;
}
.child{
position: fixed;
top: 20px;
left: 20px;
width: 200px;
height: 200px;
background: #9966FF;
color:#FFF;
z-index:300;
}
.parentSibling{
position:fixed;
background:red;
height:100px;
width:100px;
bottom:10px;
left:100px;
z-index:150;
}
@keyframes move{
0% {transform:translateX(10px);}
50% {transform:translateX(50px);}
100% {transform:translateX(10px);}
}
此时若不考虑parent的animation属性,child应该相对于窗口定位,但是实际不是的,此时child是相对于parent定位,而且由于parent的z-index是100,.parentSibling的z-index是150,此时parentSibling在child上层
如图:
造成这种现象的原因:
当元素祖先的 transform 属性非 none 时,定位容器由视口改为该祖先,这里并不是指父级元素,而是指组件元素。
transform造成影响的原理:
在规范中有规定:如果元素的transform值不为none,则该元素会生成包含块和层叠上下文。
原文:https://www.w3.org/TR/css-transforms-1/#issue-ca2c412c
This module defines a set of CSS properties that affect the visual rendering of elements to which those properties are applied; these effects are applied after elements have been sized and positioned according to the visual formatting model from [CSS2]. Some values of these properties result in the creation of a containing block, and/or the creation of a stacking context.
transtorm属性对普通元素的影响
1,transform提升元素的垂直地位
实例:https://www.zhangxinxu.com/study/201505/css3-transform-cover.html
2,transform限制position:fixed的跟随效果
实例如上
3,transform改变overflow对absolute元素的限制
实例:https://www.zhangxinxu.com/study/201505/css3-transform-overflow.html
4,transform限制absolute的100%宽度大小
实例:https://www.zhangxinxu.com/study/201505/css3-transform-absolute-percent-100.html
5,在mac safari浏览器下,使用transform: translate3d(0,0,0)
可以避免文字在其他元素transition
或animation
时候,粗细渲染跟着变化的问题