zoukankan      html  css  js  c++  java
  • CSS3 粘性定位实现吸顶 position: sticky

    粘性定位 是 相对定位(relative)和 固定定位(fixed)的混合。元素在跨越特定阈值前为相对定位,之后为固定定位。著作权归作者所有。

    它主要用在对scroll事件的监听上;简单来说,在滑动过程中,某个元素距离其父元素的距离达到sticky粘性定位的要求时(比如top:100px);position:sticky这时的效果相当于fixed定位,固定到适当位置。

    注意:起作用的,除了 top 值,还有right、left、bottom。

    常见的吸顶、吸底(移动端网站的头部返回栏,底部切换栏之类)的效果,都可以用这个属性实现。

    举个例子:

    <!DOCTYPE html>
    <html>
    <meta charset="utf8">
    <head>
    <style>
    section:first-child {
        height: 200px;
        background-color: lightgray;
    }
    section:nth-child(2) {
        height: 100px;
        background-color: orange;
        position: sticky;
        position: -webkit-sticky;
        top: 50px;
    }
    section:nth-child(3) {
        height: 300px;
        background-color: lightgray;
    }
    section:nth-child(4) {
        height: 100px;
        background-color: orange;
        position: sticky;
        position: -webkit-sticky;
        top: 150px;
    }
    section:last-child {
        height: 500px;
        background-color: darkgray;
    }
    </style>
    </head>
    <body>
    <section>SECTION-1</section>
    <section>SECTION-2</section>
    <section>SECTION-3</section>
    <section>SECTION-4</section>
    <section>SECTION-5</section>
    </body>
    </html>

    粘性定位的固定定位并不一定是position:fixed,只有目标元素的任意父元素都没有设置position:relative | absolute | fixed | sticky的情况下,才与position: fixed表现一样。而当其任一父元素设置了position:relative | absolute | fixed | sticky时,目标元素是相对于父元素的固定。

    在 https://caniuse.com/ 这个网站能查看 API 的支持情况:

     webkit 内核的浏览器需要在属性值加前缀“-webkit”才能使用。

    position: sticky;
    position: -webkit-sticky;
  • 相关阅读:
    接口测试断言详解(Jmeter)
    接口测试参数化详解(Jmeter)
    记一次线上内存泄漏问题的排查过程
    BI入门经典(转载)
    图形初阶
    数据的输入
    来自 Google 的 R 语言编码风格指南
    提醒程序员注意的一些事项--R
    R语言-attach、detach、with
    R数据类型
  • 原文地址:https://www.cnblogs.com/momo798/p/13580342.html
Copyright © 2011-2022 走看看