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;
  • 相关阅读:
    day21--案例源码详解
    字节流,字符流文件复制总结,包含9种方法,都是标准写法
    字符流总结--Day21
    重踏学习Java路上_Day21(字符流,io小结,案例)
    IO流总结--Day20
    递归总结—-day20
    重踏学习Java路上_Day20(递归,IO流)
    File总结_day19
    题解 【POJ1934】 Trip
    题解 【POJ1952】 BUY LOW, BUY LOWER
  • 原文地址:https://www.cnblogs.com/momo798/p/13580342.html
Copyright © 2011-2022 走看看