今天在写页面的时候发现个匪夷所思的问题
直接看代码吧!
// 首先来看下css代码
<body>
<style>
.box {
height: 300px;
background-color: #ddd;
}
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 30px;
background-color: green;
}
</style>
<div style="margin-top:100px"></div>
<div class="box">
我是容器box
<div class="fixed">
我是绝对定位
</div>
</div>
</body>
这样布局应该很直观;
但是在代码里面加一行属性
// 再来瞅一瞅css的代码
<body>
<style>
.box {
height: 300px;
background-color: #ddd;
transform: translate(0, 0);
}
.fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 30px;
background-color: green;
}
</style>
<div style="margin-top:100px"></div>
<div class="box">
我是容器box
<div class="fixed">
我是绝对定位
</div>
</div>
</body>
什么 fixed定位居然实效了 !!!
这是什么原因呢 !
于是我就查阅大量的资料,终于找到了答案~
这里写明了,如果父元素里有transform属性, 其属性的值不为none的话 就会创建一个堆叠上下文区域。
在这里使用的定位的 fixed , absolute 不在以文档的左顶点为基准, 而是以这个新创建的上下文区域的左顶点为基准~ 所以这个问题就找到了答案~
本人3年左右的前端开发经验,欢迎大家一起来讨论学习!