0
点赞
收藏
分享

微信扫一扫

终于用到 position:sticky 了

何以至千里 2021-09-24 阅读 131
基础前端

这是项目中一个真实的诉求,demo 代码演示如下,一个父盒子有两个子盒子,其中一个子盒子和父盒子长度一致,另一个子盒子宽度大大的超过父亲,此时要想让那个宽度等于父盒子宽度的那个子盒子,一直固定出现在父盒子里面,不随滚动条移动,但是你会发现失效,无论我们使用固定还是浮动,都不无法实现我们要的效果,我能想到的就是用 JS 。

我们遇到的问题:



演示代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>终于用到 position:sticky 了</title>
    <style>
        *{margin:0;padding:0;}
        section{
            height:200px;
            width: 400px;
            background-color: #78d48c;
            overflow: auto;
            margin: 100px auto;
        }
        header{
            width: 800px;
            height: 100px;
            background-color: #5b5ee3;
        }
        /*footer无论是position还是float都无法固定在section里面不动*/
        footer{
            height: 50px;
            background-color: #9b8207;
        }
    </style>
</head>
<body>
    <section>
        <header>
            I'm very very very very very very very very very very very very long
        </header>
        <footer>

        </footer>
    </section>
</body>
</html>

我们期望的效果:


演示代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>终于用到 position:sticky 了</title>
    <style>
        *{margin:0;padding:0;}
        section{
            height:200px;
            width: 400px;
            background-color: #78d48c;
            overflow: auto;
            margin: 100px auto;
        }
        header{
            width: 800px;
            height: 100px;
            background-color: #5b5ee3;
        }
        /*footer无论是position还是float都无法固定在section里面不动*/
        footer{
            height: 50px;
            background-color: #9b8207;
            position: sticky;
            left: 0;
        }
    </style>
</head>
<body>
    <section>
        <header>
            I'm very very very very very very very very very very very very long
        </header>
        <footer>
            我被固定住了,这是经典的滚动定位
        </footer>
    </section>
</body>
</html>

然后下面这个动图是我项目的演示示例,Antd 表格无限下拉虚拟滚动。


position:sticky 的教程查看下面两个张大大的博客:

总结:

  1. position:sticky 可以看出是 position:relative(就和相对定位效果表现一致) 和 position:fixedsticky 的 fixed 是针对最近滚动盒子,不同于真正的 fixed 相当于 window 窗口) 的结合体。

  2. 如果粘性定位设置的是 top 或 left ,盒子会先表现出来 relative ,然后在表现出 fixed

  3. 如果粘性定位设置的是 bottom 或 right ,盒子会先表现出来 fixed ,然后在表现出 relative

  4. 粘性盒子计算规则,就是在父盒子的范围里表现出对爷爷的粘性定位。

举报

相关推荐

0 条评论