【趣味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. (Inother words, it's anything except static.)A relatively positioned element is an element whose computed position value is relative. The top and bottomproperties specify the verticaloffset 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 properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relativeto which the element is positioned.) If the element has margins, they are added to the offset. The element establishes a new block formattingcontext (BFC) for its contents.A stickily positioned element is an element whose computed position value is sticky. It's treated as relativelypositioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or thecontainer 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 theircontents. However, non-replaced, absolutely positioned elements can be made to fill the available vertical space by specifying both topand bottom and leaving heightunspecified (that is, auto). They can likewise be made to fill the available horizontal space by specifying bothleft 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 rightwins when direction is rtl (Persian, Arabic, Hebrew, etc.).Accessibility concernsEnsure that elements positioned with an absolute or fixed value do not obscure other content when the page is zoomedto increase text size.MDN Understanding WCAG, Guideline 1.4 explanationsVisual Presentation: Understanding SC 1.4.8 | Understanding WCAG 2.0Performance & AccessibilityScrolling elements containing fixed or sticky content can cause performance and accessibility issues. As a userscrolls, the browser must repaint the sticky or fixed content in a new location. Depending on the content needing to be repainted, the browser performance,and the device's processing speed, the browser may not be able to manage repaints at 60 fps, causing accessibility concerns for people withsensitivities 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 therefore 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. (Inother words, it's anything except static.)A relatively positioned element is an element whose computed position value is relative. The top and bottomproperties specify the verticaloffset 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 properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relativeto which the element is positioned.) If the element has margins, they are added to the offset. The element establishes a new block formattingcontext (BFC) for its contents.A stickily positioned element is an element whose computed position value is sticky. It's treated as relativelypositioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or thecontainer 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 theircontents. However, non-replaced, absolutely positioned elements can be made to fill the available vertical space by specifying both topand bottom and leaving heightunspecified (that is, auto). They can likewise be made to fill the available horizontal space by specifying bothleft 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 rightwins when direction is rtl (Persian, Arabic, Hebrew, etc.).Accessibility concernsEnsure that elements positioned with an absolute or fixed value do not obscure other content when the page is zoomedto increase text size.MDN Understanding WCAG, Guideline 1.4 explanationsVisual Presentation: Understanding SC 1.4.8 | Understanding WCAG 2.0Performance & AccessibilityScrolling elements containing fixed or sticky content can cause performance and accessibility issues. As a userscrolls, the browser must repaint the sticky or fixed content in a new location. Depending on the content needing to be repainted, the browser performance,and the device's processing speed, the browser may not be able to manage repaints at 60 fps, causing accessibility concerns for people withsensitivities 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 therefore 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.mzph.cn/news/643243.shtml

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

相关文章

sublime text 开启vim模式

sublime text 开启vim模式 打开配置文件 mac下点击菜单栏 Sublime Text -> Settings... -> Settings 修改配置文件并保存 添加配置 // 开启vim模式 "ignored_packages": [// "Vintage", ], // 以命令模式打开文件 "vintage_start_in_comman…

视频监控平台EasyCVR增加fMP4流媒体视频格式及其应用场景介绍

近期我们在视频监控管理平台EasyCVR系统中新增了HTTP-FMP4播放协议&#xff0c;今天我们就来聊聊该协议的特点和应用。 fMP4&#xff08;Fragmented MPEG-4&#xff09;是基于MPEG-4 Part 12的流媒体格式&#xff0c;是流媒体的一项重要技术&#xff0c;因为它能通过互联网传送…

【GitHub项目推荐--12 年历史的 PDF 工具开源了】【转载】

最近在整理 PDF 的时候&#xff0c;有一些需求普通的 PDF 编辑器没办法满足&#xff0c;比如 PDF 批量合并、编辑等。 于是&#xff0c;我就去 GitHub 上看一看有没有现成的轮子&#xff0c;发现了这个 PDF 神器「PDF 补丁丁」&#xff0c;让人惊讶的是这个 PDF 神器有 12 年的…

RabbitMQ进阶篇【理解➕应用】

&#x1f973;&#x1f973;Welcome 的Huihuis Code World ! !&#x1f973;&#x1f973; 接下来看看由辉辉所写的关于RabbitMQ的相关操作吧 目录 &#x1f973;&#x1f973;Welcome 的Huihuis Code World ! !&#x1f973;&#x1f973; 一.什么是交换机 1.概念释义 2.例…

【数据分析】matplotlib、numpy、pandas速通

教程链接&#xff1a;【python教程】数据分析——numpy、pandas、matplotlib 资料&#xff1a;https://github.com/TheisTrue/DataAnalysis 1 matplotlib 官网链接&#xff1a;可查询各种图的使用及代码 对比常用统计图 1.1 折线图 &#xff08;1&#xff09;引入 from …

51单片机LCD1602调试工具

参考视频&#xff1a;江协科技51单片机 LCD1602头文件代码 #ifndef __LCD1602_H__ #define __LCD1602_H__//用户调用函数&#xff1a; void LCD_Init(); void LCD_ShowChar(unsigned char Line,unsigned char Column,char Char); void LCD_ShowString(unsigned char Line,un…

【深度学习】线性回归模型与梯度下降法

线性回归模型与梯度下降法 线性回归模型与枚举法 线性回归模型定义: w:权重b:偏置#mermaid-svg-ZAxF27Mw5dXNQgw2 {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-ZAxF27Mw5dXNQgw2 .error-icon{fill:#552222;}…

机械硬件知识学习

目录 1.电机减速机、扭矩2.伺服电机、步进电机、直线电机3.电机马达的曲线运动是如何转化为轴的直线运动 大佬科普运动控制系统链接&#xff1a;https://www.cnblogs.com/cariohu/p/15508175.html 自己对机械知识的了解是盲区&#xff0c;学习下接触到的一些硬件知识&#xff0…

含源码|基于MATLAB的去雾系统(5种去雾算法+1种本文的改进算法)

去雾系统V2包括作者新加入的多尺度Retinex去雾算法以及改进去雾算法&#xff0c;以及4种评价去雾效果的客观指标。 00 目录 引言 去雾系统新增功能 结果分析 源码获取 展望 参考文献 01 引言 在作者前面写过的文章中&#xff0c;已经介绍过图像去雾算法的应用价值及研究现…

绝地求生:本周三停机维护更新4小时: RASH悲喜套装即将下线!

本周三将迎来停机维护更新四小时~&#xff0c;同时游戏商城内RASH悲喜联名套装即将下线&#xff0c;同时空投签到任务和荣都地图翻牌任务即将下线~ 预计维护时间: 2024年1月24日08:00~12:00 本周地图轮换情况 (1月24日 ~ 1月31日) 可自主选择地图的地区:艾伦格、泰戈、帝斯顿、…

DL/T 645 协议学习笔记

一、多功能电能表通信协议 DL/T645多功能电能表通信协议&#xff08;Multi-function watt-hour meter communication protocol&#xff09;标准是为统一和规范电能表的多功能电能表与数据终端设备进行数据交换时的物理连接和协议。 1、RS-485 标准串行电气接口 本标准采用 RS-…

5.Python爬虫前的准备工作

知识准备 1) Python语言 Python 爬虫作为 Python 编程的进阶知识&#xff0c;要求具备较好的 Python 编程基础 了解 Python 语言的多进程与多线程&#xff0c;并熟悉正则表达式语法&#xff0c;也有助于编写爬虫程序 2) Web前端 了解 Web 前端的基本知识&#xff0c;比如 …

用Netty手写Http/Https服务器

Netty是一个以事件驱动的异步通信网络框架&#xff0c;可以帮助我们实现多种协议的客户端和服务端通信&#xff0c;话不多说&#xff0c;上代码&#xff0c;需要引入下方依赖 <dependency><groupId>io.netty</groupId><artifactId>netty-all</artif…

BUU LFI COURSE 1

靶场教程 1.开局界面&#xff0c;已给出源代码。2.存在文件包含include &#xff0c;直接通过传参 file 进行获取 flag。3.通过访问 url 发现报错&#xff0c;说明 flag 并不在当前目录下&#xff0c;只需要向前访问目录即可。 http://b6ed0fd6-c852-40d0-b285-32d9d00fbf00.…

抖去推短视频矩阵系统+实景无人直播系统技术源头开发

抖去推爆款视频生成器&#xff0c;通过短视频矩阵、无人直播&#xff0c;文案引流等&#xff0c;打造实体商家员工矩阵、用户矩阵、直播矩阵&#xff0c;辅助商家品牌曝光&#xff0c;团购转化等多功能赋能商家拓客引流。 短视频矩阵通俗来讲就是批量剪辑视频和批量发布视频&a…

查询小世界账号网页HTML源码

HTML源码&#xff0c;记事本打开后可以修改里面的内容&#xff0c;电脑本地双击html可以查看效果&#xff0c;复制小世界个人主页链接就可以查询QQ号&#xff0c; 蓝奏云&#xff1a;https://wfr.lanzout.com/ihXCn1lz2jnc

4G物联网LED智慧路灯杆显示屏产品介绍

4GLED显示屏是一种具有4G网络连接功能的LED显示屏。它可以通过4G网络连接到互联网&#xff0c;实现远程管理和控制&#xff0c;方便进行内容更新和管理。同时&#xff0c;4GLED显示屏具有高亮度、高清晰度和高对比度的特点&#xff0c;可以提供清晰明亮的图像和视频展示效果。它…

omron adept控制器维修SmartController EX

欧姆龙机器人adept运动控制器维修SmartController EX 19300-000 维修范围&#xff1a;姆龙机器人&#xff1b;码垛机器人&#xff1b;搬运机器人&#xff1b;焊机机器人&#xff1b;变位机等。 Adept Viper s650/s850用于装配、物料搬运、包装和机械装卸&#xff0c;循环周期短…

二进制?十进制!(C语言刷题)(位运算)

专栏:https://blog.csdn.net/2301_79293429/category_12545690.html 题目描述 给定两个十进制整数 : A,B 你需要把它们的二进制形式以十进制的运算法则相加输出结果。 例如&#xff1a; A3,B2的时候&#xff0c;A 的二进制表示是 : 11 , B 的二进制表示是 10 &#xff0c;…

物流实时数仓——概述与准备工作

目录 一、架构设计与技术栈 (一)数仓架构设计 (二)所用技术栈 (三)最终效果 二、关于离线与实时的相关概念 三、实时数仓设计思路 一、架构设计与技术栈 (一)数仓架构设计 (二)所用技术栈 Hadoop 3.3.4 Zookeeper 3.7.1 Kafka 3.3.1 Hbase 2.4.11 Redis 6.0.8 Flink 1.17…