position:fixed怎么参照祖先元素定位以及transfrom属性对元素布局的影响的原理

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) 可以避免文字在其他元素transitionanimation时候,粗细渲染跟着变化的问题

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值