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

🚀 个人主页 极客小俊
✍🏻 作者简介: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的帮助才可以!

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

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

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

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

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【产品交互】超全面B端设计规范总结

不知不觉已经深耕在B端这个领域3年有余&#xff0c;很多人接触过B端后会觉得乏味&#xff0c;因为B端的设计在视觉上并没有C端那么有冲击力&#xff0c;更多的是结合业务逻辑&#xff0c;设计出符合业务需求的交互&#xff0c;以及界面排版的合理性&#xff0c;达到产品的可用性…

UE5 C++ Slate独立程序的打包方法

在源码版安装目录内找到已编译通过的xxx.exe&#xff0c;&#xff08;\Engine\Binaries\Win64\xxx.exe)&#xff0c;在需要的位置新建文件夹&#xff0c;拷贝源码版Engine内的Binaries、Content、Shaders文件夹到目标文件夹内&#xff0c;将xxx.exe放入对应位置&#xff0c;删除…

npm或者pnpm或者yarn安装依赖报错ENOTFOUND解决办法

如果报错说安装依赖报错&#xff0c;大概率是因为npm源没有设置对&#xff0c;比如我这里安装protobufjs的时候报错&#xff1a;ENOTFOUND npm ERR! code ENOTFOUND npm ERR! syscall getaddrinfo npm ERR! errno ENOTFOUND npm ERR! network request to https://registry.cnpm…

IP地址和端口

1. IP地址&#xff1a; 简介&#xff1a; IP 协议是为计算机网络相互连接进行通信而设计的协议。在因特网中&#xff0c;它是能使连接到网上的所 有计算机网络实现相互通信的一套规则&#xff0c;规定了计算机在因特网上进行通信时应当遵守的规则。任 何厂家生产的计算机系统…

BioTech - 量子化学与分子力场

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/135787607 量子化学是应用量子力学的规律和方法来研究化学问题的一门学科&#xff0c;主要关注分子的结构、性质和反应过程。 量子化学的理论方法…

Spring Boot引起的“堆外内存泄漏”排查及经验总结

Spring Boot引起的“堆外内存泄漏”排查及经验总结 背景 为了更好地实现对项目的管理&#xff0c;我们将组内一个项目迁移到MDP框架&#xff08;基于Spring Boot&#xff09;&#xff0c;随后我们就发现系统会频繁报出Swap区域使用量过高的异常。笔者被叫去帮忙查看原因&…

web安全学习笔记【05】——反弹Shell、正反向连接

思维导图 #知识点&#xff1a; 1、Web常规-系统&中间件&数据库&源码等 2、Web其他-前后端&软件&Docker&分配站等 3、Web拓展-CDN&WAF&OSS&反向&负载均衡等 ----------------------------------- 1、APP架构-封装&原生态&H5&am…

SpringMVC 注解配置SpringMVC

文章目录 1、创建初始化类&#xff0c;代替web.xml2、创建SpringConfig配置类&#xff0c;代替spring的配置文件3、创建WebConfig配置类&#xff0c;代替SpringMVC的配置文件4、测试功能 使用配置类和注解代替web.xml和SpringMVC配置文件的功能 1、创建初始化类&#xff0c;代替…

SpringBoot3集成Zookeeper

标签&#xff1a;Zookeeper3.8 &#xff0c;Curator5.5&#xff1b; 一、简介 ZooKeeper是一个集中的服务&#xff0c;用于维护配置信息、命名、提供分布式同步、提供组服务。分布式应用程序以某种形式使用所有这些类型的服务。 二、环境搭建 1、修改配置文件 # 1、拷贝一份…

前端面试题-(浏览器内核,CSS选择器优先级,盒子模型,CSS硬件加速,CSS扩展)

前端面试题-(浏览器内核&#xff0c;CSS选择器优先级&#xff0c;盒子模型&#xff0c;CSS硬件加速&#xff0c;CSS扩展&#xff09; 常见的浏览器内核CSS选择器优先级盒子模型CSS硬件加速CSS扩展 常见的浏览器内核 内核描述Trident(IE内核)主要用在window系统中的IE浏览器中&…

云原生离线工作流编排利器 -- 分布式工作流 Argo 集群

作者&#xff1a;庄宇 在现代的软件开发和数据处理领域&#xff0c;批处理作业&#xff08;Batch&#xff09;扮演着重要的角色。它们通常用于数据处理&#xff0c;仿真计算&#xff0c;科学计算等领域&#xff0c;往往需要大规模的计算资源。随着云计算的兴起&#xff0c;阿里…

L1-093 猜帽子游戏(Java)

宝宝们在一起玩一个猜帽子游戏。每人头上被扣了一顶帽子&#xff0c;有的是黑色的&#xff0c;有的是黄色的。每个人可以看到别人头上的帽子&#xff0c;但是看不到自己的。游戏开始后&#xff0c;每个人可以猜自己头上的帽子是什么颜色&#xff0c;或者可以弃权不猜。如果没有…

人工智能≠机器“人”:激活基础模型在产业中的巨大应用潜力和商业价值

编者按&#xff1a;2023年是微软亚洲研究院建院25周年。借此机会&#xff0c;我们特别策划了“智启未来”系列文章&#xff0c;邀请到微软亚洲研究院不同研究领域的领军人物&#xff0c;以署名文章的形式分享他们对人工智能、计算机及其交叉学科领域的观点洞察及前沿展望。希望…

数据结构顺序表

思维导图 练习 头文件 1 #ifndef __HEAD_H__2 #define __HEAD_H__3 4 5 #include <stdio.h>6 #include <string.h>7 #include <stdlib.h>8 9 10 #define MAXSIZE 711 typedef int datatype;12 enum13 {14 FLASE-1,15 SUCCESS16 };17 //定义顺序表&a…

在Vite5.x中使用monaco-editor

Uncaught (in promise) Error: Unexpected usage at _EditorSimpleWorker.loadForeignModule 如果你像我这样报错,那一般是getWorker部分出问题了. 首先推个帖子: https://github.com/vitejs/vite/discussions/1791 然后是代码 不需要在vite.config.ts中做任何设置,也不用…

RabbitMQ 入门到精通

RabbitMQ入门到精通 一、了解RabbitMQ1.基础知识2.多种交换机模型详解 二、服务端搭建1.简单搭建2.信息持久化到容器外部 三、消息生产者和消费者1.消息生产者2.消息消费者3.RabbitTemplate 详解4.RabbitListener详解5.其他注解 四、如何保证消息可靠性1.发送方进行消息发送成功…

[笔记]Spring AOP

Spring AOP&#xff08;Aspect Oriented Programming&#xff09; AOP将应用程序分为核心业务和非核心的公共功能&#xff0c;AOP的关注点是系统中的非核心的公共功能&#xff1b; AOP可以通过预编译或者运行期动态代理的方式&#xff0c;为横跨多个对象&#xff08;没有继承关…

Elasticsearch:Simulate ingest API

Ingest pipeline 为我们摄入数据提供了极大的方便。在我之前的文章中&#xff0c;有非常多的有关 ingest pipeline 的文章。请详细阅读文章 “Elastic&#xff1a;开发者上手指南”。针对一组提供的文档执行摄取管道&#xff0c;可以选择使用替代管道定义。 Simulate ingest AP…

Parallels Desktop 19 mac 虚拟机软件 兼容M1 M2

Parallels Desktop 19 for Mac 是一款适用于 macOS 的虚拟机软件。无需重启即可在 Mac 上运行 Windows、Linux 等系统&#xff0c;具有速度快、操作简单且功能强大的优点。包括 30 余种实用工具&#xff0c;可简化 Mac 和 Windows 上的日常任务。 软件下载&#xff1a;Parallel…

小新22-IAP,24-IAP,27-IAP(F0GG,F0GH,F0GJ)原厂Win11.22H2系统

lenovo联想小新22寸,24寸,27寸IAP原装出厂Windows11系统镜像还原包&#xff0c;恢复出厂开箱状态 适用型号&#xff1a; 联想小新27-IAP(F0GJ),小新24-IAP(F0GH),小新22-IAP(F0GG) IdeaCentre AIO 3 22IAP7,IdeaCentre AIO 3 24IAP7,IdeaCentre AIO 3 27IAP7 链接&#xff1…