最近项目中,对于一些元素使用了fixed(
相对于屏幕视口(viewport)的位置来指定元素位置),但是却出现一些特殊的现象:使用了position:fixed;top:0;left:0的元素,居然不是处于窗口的左上角,且会跟着滚动条一起滚动。本文针对这个现象的疑惑,做个解释以及对应的解决方案
1、现象
对于小图标,使用fixed定位
position:fixed;
top:0;
left:0
该图标不是按照预想的,处于最左边。检查了一下,发现是ui在蓝湖里使用的backdrop-filter: blur(2px)样式,实现背景模糊,但是却改变了fixed原先的效果,且滚动后也会跟着滚动
2、position:fixed
元素会被移出正常文档流,并不为元素预留空间,而是通过指定元素相对于屏幕视口(viewport)的位置来指定元素位置。元素的位置在屏幕滚动时不会改变。打印时,元素会出现在的每页的固定位置。fixed 属性会创建新的层叠上下文。当元素祖先的 transform、perspective、filter 或 backdrop-filter 属性非 none 时,容器由视口改为该祖先
3、解决方案
- 可以把这些会改变祖先的样式,放在兄弟元素上
- 使用伪元素
4、测试案列
- 放在兄弟元素
<div style="height: 18000px;width: 300px;background-image: url(https://xxx.xxxxx.xxxx/gc-assets/popstone2/popstone2_icon.png);">
<div
style="backdrop-filter:blur(2px); height: 300px; width:300px;">
</div>
<div style="position: fixed;top:0;left: 0; height: 300px;width: 300px;"></div>
</div>
- 使用伪元素
<style>
.filter::before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
backdrop-filter: blur(2px);
}
</style>
<div style="height: 18000px;width: 300px;background-image: url(https://xxx.xxxxx.xxx/gc-assets/popstone2/popstone2_icon.png);">
<div class="filter" style="position: fixed;top:0;left: 0; height: 300px;width: 300px;"></div>
</div>
效果如下: 不管怎么滚动,都处于左上角