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;
  • 相关阅读:
    基础JavaScript练习(一)总结
    零基础JavaScript编码(三)总结
    零基础JavaScript编码(二)
    零基础JavaScript编码(一)
    响应式网格(栅格化)布局总结
    实现常见的技术产品官网的页面架构及样式布局总结
    通过HTML及CSS模拟报纸排版总结
    任务四:定位和居中问题总结
    1. Two Sum
    任务三:三栏式布局总结
  • 原文地址:https://www.cnblogs.com/momo798/p/13580342.html
Copyright © 2011-2022 走看看