【趣味CSS3.0】粘性定位属性Position:sticky是不是真的没用了?

news2024/10/6 10:35:04

🚀 个人主页 极客小俊
✍🏻 作者简介:web开发者、设计师、技术分享博主
🐋 希望大家多多支持一下, 我们一起学习和进步!😄
🏅 如果文章对你有帮助的话,欢迎评论 💬点赞👍🏻 收藏 📂加关注

概述

我们以前在定位属性当中学习过relative、absolute、fixed、static这几种定位,但是后来的CSS3中出现了一种新的定位方式叫sticky, 它的中文意思是粘性的意思, 所以我们称之为粘性定位

那么什么叫粘性定位呢,它又有什么用处呢?

不用着急 哈哈哈 我们先来看一个案例你就明白了!

如图

从上图案例中我们可以看到 导航菜单滚动条啦到一定位置的时候,就自动吸附在了某个位置上!

虽然这个吸附粘性效果我们是可以通过javascript脚本去实现,但是现在我们有了CSS3中的sticky定位就可以很方便的去实现这个效果!

所以我们的粘性定位(sticky) 也就是基于用户的滚动条位置来定位元素的定位的,这就是所谓的粘性!

粘性定位的定义

首先既然是定位,那么肯定也是依靠元素本身对吧, 那么粘性定位的元素主要依赖于用户的滚动, 这里的滚动通常都是指的滚动条!

sticky就像是relativefixed的结合体一样, 也就是说当一个元素设置了sticky定位之后,会根据表现为在跨越特定阈值前为相对定位,之后为固定定位, 而这个特定阈值指的是 top、right、bottom、left之一

简单点说我们给一个元素设置的sticky定位,那么必须指定一个top, right, bottom 或 left 这4个阈值其中一个才可以使粘性定位生效, 否则就跟相对定位一样, 没什么效果可言!

案例

我们来看一个案例,假设我们随便来一点文字信息,把它们装到一个容器里面,
然后里面再添加一个div给它设置粘性定位看看效果

代码如下

<style type="text/css">
    #info{
        width: 100px;
        height: 30px;
        line-height: 30px;
        color: white;
        background-color: green;
        border: 2px solid black;
        padding: 5px;
        margin: 100px auto;
        font-weight: bold;
        text-align: center;
    }
    .box1 {
        width: 500px;
        height: 700px;
        background: yellow;
        margin: 100px auto;
        overflow-y: scroll;
    }

    .box1>.box2{
        background-color: blue;
        width: auto;
        height: 50px;
        /*开始进行粘性定位,黏住元素, 在指定的top和left位置 黏住元素*/
        position: sticky;
        top: 50px;
        left:0px;
    }
</style>


<div class="box1" id="box1">
    <div class="box2" id="box2"></div>
    A positioned element is an element whose computed position value is either relative, absolute, fixed, or sticky. (In
    other words, it's anythi
    ng except static.)
    A relatively positioned element is an element whose computed position value is relative. The top and bottom
    properties specify the vertical
    offset from its normal position; the left and right properties specify the horizontal offset.
    An absolutely positioned element is an element whose computed position value is absolute or fixed. The top, right,
    bottom, and left properti
    es specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative
    to which the element is positi
    oned.) If the element has margins, they are added to the offset. The element establishes a new block formatting
    context (BFC) for its contents.
    A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively
    positioned until its contai
    ning block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the
    container it scrolls within),
    at which point it is treated as "stuck" until meeting the opposite edge of its containing block.
    Most of the time, absolutely positioned elements that have height and width set to auto are sized so as to fit their
    contents. However, n
    on-replaced, absolutely positioned elements can be made to fill the available vertical space by specifying both top
    and bottom and leaving height
    unspecified (that is, auto). They can likewise be made to fill the available horizontal space by specifying both
    left and right and leaving width as auto.

    Except for the case just described (of absolutely positioned elements filling the available space):

    If both top and bottom are specified (technically, not auto), top wins.
    If both left and right are specified, left wins when direction is ltr (English, horizontal Japanese, etc.) and right
    wins when direction is rtl (Persian, Arabic, Hebrew, etc.).
    Accessibility concerns
    Ensure that elements positioned with an absolute or fixed value do not obscure other content when the page is zoomed
    to increase text size.

    MDN Understanding WCAG, Guideline 1.4 explanations
    Visual Presentation: Understanding SC 1.4.8 | Understanding WCAG 2.0
    Performance & Accessibility
    Scrolling elements containing fixed or sticky content can cause performance and accessibility issues. As a user
    scrolls, the browser must repaint the st
    icky or fixed content in a new location. Depending on the content needing to be repainted, the browser performance,
    and the device's process
    ing speed, the browser may not be able to manage repaints at 60 fps, causing accessibility concerns for people with
    sensitivities and jank for everyone.
    One solution is to add will-change: transform to the positioned elements to render the element in its own layer,
    improving repaint speed and therefor
    e improving performance and accessibility.

</div>

效果如下

分析

上图的代码中,我们可以看到,给元素box2定义了sticky定位同时指定了一个top:50px,意思就是直接把元素固定到了距离顶部50px的位置,相当于设置了fixed定位一样!

所以其实意思很简单:给元素一开始开始进行设置sticky粘性定位,然后再指定的top或者left等位置,黏住元素!

其实这样看,我们还不好看出区别,我们可以把代码修改一下,并且用javascript来监测一下效果!

html代码


<div id="info">没有开始吸附</div>
<div class="box1" id="box1">
    <div class="box2" id="box2"></div>
    A positioned element is an element whose computed position value is either relative, absolute, fixed, or sticky. (In
    other words, it's anythi
    ng except static.)
    A relatively positioned element is an element whose computed position value is relative. The top and bottom
    properties specify the vertical
    offset from its normal position; the left and right properties specify the horizontal offset.
    An absolutely positioned element is an element whose computed position value is absolute or fixed. The top, right,
    bottom, and left properti
    es specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative
    to which the element is positi
    oned.) If the element has margins, they are added to the offset. The element establishes a new block formatting
    context (BFC) for its contents.
    A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively
    positioned until its contai
    ning block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the
    container it scrolls within),
    at which point it is treated as "stuck" until meeting the opposite edge of its containing block.
    Most of the time, absolutely positioned elements that have height and width set to auto are sized so as to fit their
    contents. However, n
    on-replaced, absolutely positioned elements can be made to fill the available vertical space by specifying both top
    and bottom and leaving height
    unspecified (that is, auto). They can likewise be made to fill the available horizontal space by specifying both
    left and right and leaving width as auto.

    Except for the case just described (of absolutely positioned elements filling the available space):

    If both top and bottom are specified (technically, not auto), top wins.
    If both left and right are specified, left wins when direction is ltr (English, horizontal Japanese, etc.) and right
    wins when direction is rtl (Persian, Arabic, Hebrew, etc.).
    Accessibility concerns
    Ensure that elements positioned with an absolute or fixed value do not obscure other content when the page is zoomed
    to increase text size.

    MDN Understanding WCAG, Guideline 1.4 explanations
    Visual Presentation: Understanding SC 1.4.8 | Understanding WCAG 2.0
    Performance & Accessibility
    Scrolling elements containing fixed or sticky content can cause performance and accessibility issues. As a user
    scrolls, the browser must repaint the st
    icky or fixed content in a new location. Depending on the content needing to be repainted, the browser performance,
    and the device's process
    ing speed, the browser may not be able to manage repaints at 60 fps, causing accessibility concerns for people with
    sensitivities and jank for everyone.
    One solution is to add will-change: transform to the positioned elements to render the element in its own layer,
    improving repaint speed and therefor
    e improving performance and accessibility.
</div>

css代码

<style type="text/css">


    #info{
        width: 100px;
        height: 30px;
        line-height: 30px;
        color: white;
        background-color: green;
        border: 2px solid black;
        padding: 5px;
        margin: 100px auto;
        font-weight: bold;
        text-align: center;
    }
    .box1 {
        width: 500px;
        height: 700px;
        background: yellow;
        margin: 100px auto;
        overflow-y: scroll;
    }

    .box1>.box2{
        background-color: blue;
        width: auto;
        height: 50px;
        /*当它有一定的距离*/
        margin-top: 100px;
        /*开始进行粘性定位,在指定的top和left位置 黏住元素*/
        position: sticky;
        top: 0px;
        left:0px;
    }
</style>

js代码

<script>
    window.onload=function (){

        var info=document.getElementById("info");
        var box1=document.getElementById("box1");
        var box2=document.getElementById("box2");

        box1.onscroll=function (){
            console.log(box1.scrollTop);
            //获取当前元素滚动条到顶部的Top值
            if(box1.scrollTop>=100){
                box2.style.backgroundColor="red";
                info.innerHTML="开始吸附";
                info.style.background="red";
            }else{
                box2.style.backgroundColor="blue";
                info.innerHTML="没有开始吸附";
                info.style.background="green";
            }
        }

    }

</script>


效果如下

分析

这里我们加了一个margin-top 让大家方便看吸附效果

但是如果你指定了top值 那么其实就要相应的减掉margin-top值,从而计算得到正确的粘性触发阈值!

Sticky与Fixed的区别

很多人搞不清楚这两个之间的区别,其实也很简单

fixed定位是相对于整个浏览器视窗进行固定定位和吸附的!

Sticky定位是相对于父元素进行粘性定位和吸附的!

你如果不相信,我们可以来修改一下CSS代码看看

举个栗子

.box1>.box2{
    background-color: blue;
    width: 500px; /*给一个宽度*/
    height: 50px;
    /*当它有一定的距离*/
    margin-top: 100px;
    /*开始进行粘性定位,在指定的top和left位置 黏住元素*/
    position: fixed; /*设置固定定位*/
    top: 0px;
    left:0px;
}

如图

Sticky定位的兼容性

Sticky定位的兼容性目前 比较早的低版本浏览器可能是不支持Sticky定位

我们里可以使用Edge浏览器来模拟一下ie11的内核看看有没有效果!

如图


从上图看js代码是没问题的,但很显然Sticky定位是不兼容的

最后

所以使用这个粘性定位属性也是需要看具体情况来决定, 如果你不考虑兼容性,只是考虑最新浏览器的渲染,那么基本上没什么问题,如果你要兼容老一点的浏览器,那么可能还需要借助js的帮助才可以!

"👍点赞" "✍️评论" "收藏❤️"

大家的支持就是我坚持下去的动力!

如果以上内容有任何错误或者不准确的地方,🤗🤗🤗欢迎在下面 👇👇👇 留个言指出、或者你有更好的想法,
欢迎一起交流学习❤️❤️💛💛💚💚

更多 好玩 好用 好看的干货教程可以 点击下方关注❤️ 微信公众号❤️
说不定有意料之外的收获哦..🤗嘿嘿嘿、嘻嘻嘻🤗!
🌽🍓🍎🍍🍉🍇

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1406341.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Windows下安装达梦8开发版数据库

达梦数据库属于国产主流数据库之一&#xff0c;本文记录WIndows下安装最新的达梦8数据库的过程。   达梦官网&#xff08;参考文献1&#xff09;下载开发版&#xff08;X86平台&#xff09;版安装包&#xff0c;如下图所示&#xff1a; 解压安装包后&#xff0c;其中包含ISO文…

打 jar 包运行 在windows 平台控制台和日志 乱码解决

--拒絕鷄巴囉嗦&#xff0c;直接解決問題 我们在Windows下运行jar包时&#xff0c;常常会出现乱码&#xff0c;主要分为dos窗口输出的日志中出现乱码和程序返回数据出现乱码。 dos窗口输出的日志中出现乱码 执行如下命令&#xff0c;将控制台输出编码改为UTF8&#xff1a; ch…

BL0942 内置时钟免校准计量芯片 用于智能家居领域 上海贝岭 低成本 使用指南

BL0939是上海贝岭股份有限公司开发的一款用于智能家居领域进行电能测量的专用芯片&#xff0c;支持两路测量&#xff0c;可同时进行计量和漏电故障检测&#xff0c;漏电检测电流可设&#xff0c;响应时间快&#xff0c;具有体积小&#xff0c;外围电路简单&#xff0c;成本低廉…

springboot集成tess4j

spring整合tess4j用于OCR识别图片&#xff0c;在windows环境识别正常&#xff0c;在liunx没有反应&#xff0c;本文用于解决部署linux问题。 整合springboot 1、引入pom文件 <dependency><groupId>net.sourceforge.tess4j</groupId><artifactId>tess…

HTML标题

我的HTML标题学习小记 HTML的标题功能真的非常实用&#xff01;它们就像是文章的大纲&#xff0c;帮助网页内容呈现出清晰的结构&#xff0c;也就是小题大作一番。 HTML标题的奥秘 在HTML中&#xff0c;我们使用<h1>至<h6>这些标签来定义标题。其中&#xff0c;…

​ElasticSearch

目录 简介 基本概念 倒排索引 FST 简介 ES是一个基于lucene构建的&#xff0c;分布式的&#xff0c;RESTful的开源全文搜索引擎。支持对各种类型的数据的索引&#xff1b;搜索速度快&#xff0c;可以提供实时的搜索服务&#xff1b;便于水平扩展&#xff0c;每秒可以处理 …

GitHub无法完成推送 的设置选项

GitHub无法完成推送 的设置选项 系统设置 VS中控制台设置【指令】 控制台调出方法 以下为VS控制台指令 git config --global --unset http.proxy git config --global --unset https.proxygit config --global http.proxy 127.0.0.1:7890 git config --global https.proxy …

http503错误是什么原因

HTTP503错误在站长圈很经常遇到&#xff0c;很多网站站长经常遇到的HTTP503错误经常会不知道怎么去解决它。今天我们就来针对HTTP503错误问题展开说说。HTTP503错误是指服务器暂时无法处理客户端的请求&#xff0c;常常出现在服务器超负荷或维护期间。在这种情况下&#xff0c;…

深入分析 Linux 网络丢包问题

热门IT课程【视频教程】-华为/思科/红帽/oraclehttps://xmws-it.blog.csdn.net/article/details/134398330 所谓丢包&#xff0c;是指在网络数据的收发过程中&#xff0c;由于种种原因&#xff0c;数据包还没传输到应用程序中&#xff0c;就被丢弃了。这些被丢弃包的数量&#…

canvas绘制美国国旗(USA Flag)

查看专栏目录 canvas实例应用100专栏&#xff0c;提供canvas的基础知识&#xff0c;高级动画&#xff0c;相关应用扩展等信息。canvas作为html的一部分&#xff0c;是图像图标地图可视化的一个重要的基础&#xff0c;学好了canvas&#xff0c;在其他的一些应用上将会起到非常重…

burp靶场--跨域资源共享(CORS)

burp靶场–跨域资源共享&#xff08;CORS&#xff09; https://portswigger.net/web-security/cors ### 跨域资源共享&#xff08;CORS&#xff09; 在本节中&#xff0c;我们将解释什么是跨域资源共享 (CORS)&#xff0c;描述基于跨域资源共享的攻击的一些常见示例&#xff…

链表的经典算法OJ题

前言 hello&#xff0c;大家好呀&#xff0c;我是Humble&#xff0c;本篇博客要分享的内容是关于链表的一些力扣OJ题 OK&#xff0c;废话不多说&#xff0c;我们直接开始吧~ 题目一 203. 移除链表元素 - 力扣&#xff08;LeetCode&#xff09; 题目描述&#xff1a; 给你一个…

C# 使用屏障来使多线程并发操作保持同步

写在前面 以下是微软官方对屏障类的介绍&#xff0c;System.Threading.Barrier 可用来作为实现并发同步操作的基本单元&#xff0c;让多个线程(参与者)分阶段并行处理目标算法。在达到代码中的屏障点之前&#xff0c;每个参与者将继续执行&#xff0c;屏障表示工作阶段的末尾&…

机器学习实验3——支持向量机分类鸢尾花

文章目录 &#x1f9e1;&#x1f9e1;实验内容&#x1f9e1;&#x1f9e1;&#x1f9e1;&#x1f9e1;数据预处理&#x1f9e1;&#x1f9e1;代码认识数据相关性分析径向可视化各个特征之间的关系图 &#x1f9e1;&#x1f9e1;支持向量机SVM求解&#x1f9e1;&#x1f9e1;直觉…

单调栈笔记

单调栈 1.每日温度2.下一个更大元素 I3.下一个更大的元素4.接雨水5.柱状图中最大的矩形 单调栈正如其名字&#xff0c;用一个栈&#xff08;能够实现栈性质的数据结构就行&#xff09;来存储元素&#xff0c;存储在栈中的元素保持单调性&#xff08;单调递增或者是单调递减&…

SE通道注意力机制模块

简介 论文原址&#xff1a;https://arxiv.org/pdf/1709.01507.pdf 在深度学习领域&#xff0c;提升模型的表征能力一直是一个关键的研究方向。SE&#xff08;Squeeze-and-Excitation&#xff09;模块是一种引入通道注意力机制的方法&#xff0c;旨在让神经网络更加关注对当前…

5_机械臂运动学基础_矩阵

上次说的向量空间是为矩阵服务的。 1、学科回顾 从科技实践中来的数学问题无非分为两类&#xff1a;一类是线性问题&#xff0c;一类是非线性问题。线性问题是研究最久、理论最完善的&#xff1b;而非线性问题则可以在一定基础上转化为线性问题求解。 线性变换&#xff1a; 数域…

活动回顾丨云原生技术实践营上海站「云原生 AI 大数据」专场(附 PPT)

AI 势不可挡&#xff0c;“智算”赋能未来。2024 年 1 月 5 日&#xff0c;云原生技术实践营「云原生 AI &大数据」专场在上海落幕。活动聚焦容器、可观测、微服务产品技术领域&#xff0c;以云原生 AI 工程化落地为主要方向&#xff0c;希望帮助企业和开发者更快、更高效地…

机器学习期末复习总结笔记(李航统计学习方法)

文章目录 模型复杂度高---过拟合分类与回归有监督、无监督、半监督正则化生成模型和判别模型感知机KNN朴素贝叶斯决策树SVMAdaboost聚类风险PCA深度学习范数计算梯度下降与随机梯度下降SGD线性回归逻辑回归最大熵模型适用性讨论 模型复杂度高—过拟合 是什么&#xff1a;当模型…

应用监控 eBPF 版:实现高效协议解析的技术探索

作者&#xff1a;彦鸿 引言 随着 Kuberentes 等云原生技术的飞速发展&#xff0c;带来了研发与运维模式的变革。企业软件架构由单体服务向分布式、微服务演进。随着业务发展&#xff0c;多语言、多框架、多协议的微服务在企业中越来越多&#xff0c;软件架构复杂度越来越高&a…