关于前端:css-粘性定位position-sticky-的使用

sticky 粘性定位
position: sticky; 基于用户的滚动地位来定位。
粘性定位元素的款式体现,会在 position: relative 与 position: fixed之间切换。是否满足阈值条件决定粘性定位元素的款式体现。

在这个案例中,当stiky元素的未达到阈值地位(top: 20px;)它的行为就像 position: relative;

而当页面滚动超出指标区域时,它的体现就像 position: fixed;会固定在指标地位。

如何让sticky失效:
1、须指定 top, right, bottom 或 left 四个阈值其中之一,才可使sticky失效。否则其行为始终为position: relative。

留神:当 top 和 bottom 同时设置时,top 失效的优先级高;left 和 right 同时设置时,left 的优先级高。

2、除<body>外,sticky元素的任意父元素不能为overflow: hidden || auto || scroll。 sticky元素的任意父元素必须均为 overflow: visible;

3、父元素的高度不能低于sticky元素的高度。

此外还有一些奇怪的个性:

1、通过样式表增加 z-index 有效(.class #id 的形式有效)。在sticky元素上间接增加行内 style 无效。

2、sticky 不会触发 BFC。

示例代码:
https://github.com/DiracKeeko…

其余- 兼容性测试
https://caniuse.com/?search=s…

此外检测浏览器是否反对 sticky 能够在控制台中应用如下代码测试:

if (CSS.supports("position", "sticky") || CSS.supports("position", "-webkit-sticky")) {
    console.log("support");
}

同步更新到本人的语雀
https://www.yuque.com/diracke…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理