子元素绝对定位跟随父元素overflowscroll滚动问题
写项目的时候忽然遇到一个问题, 子元素固定定位,父元素设置 overflow:scroll
超出部分滚动, 结果固定定位的元素仍然会随着滚动条滚动, 按照原先的理解,父元素内部滚动是不会影响固定定位的元素的
原先代码样例:
<div class="box">
<div class="child-1"></div>
<div class="child-2"></div>
</div>
<style>
.box {
height: 300px;
background-color: red;
padding-top: 200px;
position: relative;
overflow: scroll;
}
.child-1 {
position: absolute;
top: 0;
height: 100px;
width: 100%;
background-color: green;
z-index: 999;
}
.child-2 {
height: 400px;
background-color: deepskyblue;
}
</style>
显示效果就是child-1元素会跟随滚动条滚动
解决方法:
出现这样的问题就是因为父元素设置了position: relative;
, 父元素相对定位会导致,滚动条在滚动的同时,将父元素的位置也移动了,而child-1定位于父元素,所以会跟随父元素一起滚动.
所以我们解决方法就是在 child-2外层再套一层用于滚动的div
<div class="box">
<div class="child-1"></div>
<div class="scroll">
<div class="child-2"></div>
</div>
</div>
<style>
.box {
height: 300px;
background-color: red;
position: relative;
overflow: scroll;
}
.child-1 {
position: absolute;
top: 0;
height: 100px;
width: 100%;
background-color: green;
z-index: 999;
}
.scroll {
height: 100%;
overflow: scroll;
padding-top: 200px;
}
.child-2 {
height: 400px;
background-color: deepskyblue;
}
</style>
显示效果:
本身不是上面大问题,主要是刚碰到有点懵逼