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
時候,粗細渲染跟着變化的問題