position:sticky 粘性定位的几种巧妙应用详解
背景:position: sticky 又称为粘性定位,粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。元素根据正常文档流进行定位,然后相对它的最近滚动祖先(nearest scrolling ancestor)和 containing block (最近块级祖先 nearest block-level ancestor),包括table-related 元素,基于 top, right, bottom, 和 left的值进行偏移。
粘性定位可以被认为是相对定位和固定定位的混合。元素在跨越特定阈值前为相对定位,之后为固定定位。例如:
#one { position: sticky; top: 10px; }
设置了以上样式的元素,在 viewport 视口滚动到元素 top 距离小于 10px 之前,元素为相对定位。之后,元素将固定在与顶部距离 10px 的位置,直到 viewport 视口回滚到阈值以下。
注意:
- 元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。
- 须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
- 偏移值不会影响任何其他元素的位置。该值总是创建一个新的层叠上下文(stacking context)。
- 一个 sticky元素 会 固定 在离它最近的一个拥有 滚动机制 的祖先上(当该祖先的 overflow 是 hidden, scroll, auto, 或 overlay时),即便这个祖先不是最近的真实可滚动祖先。
应用示例
1. 基础:头部固定
头部导航栏开始时相对定位顶部,当页面元素发生滚动时,变为和 fixed 类似的固定定位。
HEADER MAIN CONTENT
.main-container { max-width: 500px; height: 500px; margin: 0 auto; margin-top: 40px; overflow: auto; } .main-container *+* { margin-top: 20px; } .main-header { height: 50px; } .main-content { min-height: 600px; } .main-header { position: -webkit-sticky; position: sticky; top: 0; }
2. 基础:页脚固定
页脚固定效果,开始时也较为固定定位效果,当页面滚动超过页脚时,页脚定位效果变为相对定位效果,可用于显示一些底部信息或广告。
HEADER MAIN CONTENT
.main-container *+* { margin-top: 20px; } .main-header { height: 50px; } .main-content { min-height: 600px; } .main-footer { position: -webkit-sticky; position: sticky; bottom: 0; border-color: red; } .devide { height: 600px; }
3. 基础:侧边栏固定
当页面产生滚动,位置超过侧边栏的 顶部阈值 后,侧边栏变为固定定位,可用于实现侧边导航栏或侧边提示信息及广告展示。
Scroll Down!
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minus suscipit blanditiis delectus quos, soluta fuga voluptatem, facere inventore neque voluptate quaerat unde laboriosam molestiae repellat, sapiente accusamus cumque! Ipsam, illo!
.cf:before, .cf:after { content: " "; display: table; clear: both; } .cf { *zoom: 1; } .scroll { height: 500px; overflow: scroll; padding: 0 10px; max-width: 500px; margin: 40px auto; background: #FFFFFF; } .content { padding: 0 15px; width: 280px; } .sidebar { padding: 20px; width: 170px; background: #2D2D2D; color: #FFFFFF; } .content, .sidebar { float: left; } .sidebar { position: -webkit-sticky; position: sticky; top: 15px; }
4. 基础:列表锚点
仅使用 css 就可实现页面滚动锚点固定效果,可用于实现通讯录滚动、日志记录滚动、其他分类列表滚动效果。
AAppleArtichokeAardvarkAntAcornDDogDateDanishDandelion
@supports CSS at-rule 您可以指定依赖于浏览器中的一个或多个特定的CSS功能的支持声明。这被称为特性查询。该规则可以放在代码的顶层,也可以嵌套在任何其他条件组规则中。
@supports (position: sticky) { .list-header { position: sticky; top: 0; } } .container { width: 500px; height: 500px; margin: 40px auto; position: relative; overflow: auto; } .list { min-height: 1600px; background: #FFFFFF; } .list-content { padding: 10px 20px; } .list-header { padding: 10px; background: #2D2D2D; color: #FFFFFF; position: relative; font-weight: bold; }
5. 进阶:表格表头固定
对 table 元素的 th 或 tr 设置 position: sticky; 可以实现表格头部或某行固定,也可将多个表格合并到一起,当滚动到当前表格是,固定头部自动变为当前表格的表头。
Name Age Job Color URL Lorem. Ullam. Vel. At. Quis. Name Age Job Color URL
.container { height: 500px; width: fit-content; margin: 40px auto; x overflow: auto; } table { text-align: left; position: relative; border-collapse: collapse; } th, td { padding: 0.25rem; } tr:nth-child(even) { background: #EFEFEF; } tr.red th { background: #dd4a63; color: white; } tr.green th { background: #03C03C; color: white; } tr.blue th { background: #1580d8; color: white; } th { background: white; position: sticky; top: 0; }
6. 进阶:页面进度条(简易)
利用 position: sticky; 定位,可以实现页面浏览进度条效果,以下是简易进度条的演示,实际实现中可将未滚动到顶部的元素设置为透明色,滚动到顶部时变为蓝色。
Sticky Progress
Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem, cumque? A, est perferendis explicabo odit possimus quisquam rem ad tempore ipsa, obcaecati ex culpa similique, aliquam corporis. Quis, nostrum expedita.
Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem, cumque? A, est perferendis explicabo odit possimus quisquam rem ad tempore ipsa, obcaecati ex culpa similique, aliquam corporis. Quis, nostrum expedita.
.container { width: 500px; height: 500px; overflow: auto; margin: 40px auto 40px; padding-bottom: 500px; box-sizing: border-box; } .sticky { width: 50px; height: 10px; background: rgba(36, 167, 254, 0.979); position: -webkit-sticky; position: sticky; top: 0; } .sticky:nth-of-type(2) { transform: translateX(50px); } .sticky:nth-of-type(3) { transform: translateX(100px); } .sticky:nth-of-type(4) { // ... .sticky:nth-of-type(10) { transform: translateX(450px); }
7. 进阶:页面进度条(优化)
优化版的进度条支持浏览进度百分比显示,助于提升用户体验。
%20%20Page Progress Bar Example
All%20images%20provided%20at%20random%20from%20Codepen%20assets.%20All%20ipsum%20text%20provided%20by%20officeipsum.com.
%20%20Face%20time%20level%20the%20playing%20field%20highlights.%20Bake%20it%20in%20quick%20win%20bench%20mark,%20or%20paddle%20on%20both%20sides.%20Re-inventing%20the%20wheel.%20What%20do%20you%20feel%20you%20would%20bring%20to%20the%20table%20if%20you%20were%20hired%20for%20this%20position%20drink%20from%20the%20firehose,%20but%20quarterly%20sales%20are%20at%20an%20all-time%20low%20or%20can%20you%20ballpark%20the%20cost%20per%20unit%20for%20me%20we%20are%20running%20out%20of%20runway.
%20%20 %20%20 %20%20Meeting%20assassin%20enough%20to%20wash%20your%20face%20so%20after%20I%20ran%20into%20Helen%20at%20a%20restaurant,%20I%20realized%20she%20was%20just%20office%20pretty%20good%20optics%20put%20a%20record%20on%20and%20see%20who%20dances,%20yet%20we're%20ahead%20of%20the%20curve%20on%20that%20one,%20or%20personal%20development.%20Bench%20mark%20beef%20up%20helicopter%20view%20highlights%20take%20five,%20punch%20the%20tree,%20and%20come%20back%20in%20here%20with%20a%20clear%20head,%20so%20translating%20our%20vision%20of%20having%20a%20market%20leading%20platfrom%20nor%20what's%20the%20status%20on%20the%20deliverables%20for%20eow?.
:root%20{ %20%20--progress-bar-height:%204px; %20%20--progress-bar-color:%20gainsboro; %20%20--progress-bar-value-color:%20dodgerblue; %20%20--progress-bar-value:%2020%; } article%20{ %20%20position:%20relative; %20%20padding:%2024px; %20%20width:%20100%; %20%20max-width:%20700px; %20%20margin:%2060px%20auto; } .article-title%20{ %20%20position:%20sticky; %20%20top:%200; %20%20padding-bottom:%2024px; } img%20{ %20%20width:%20100%; %20%20margin-bottom:%2018px; } .progress-wrapper%20{ %20%20position:%20relative; } .progress-label%20{ %20%20position:%20absolute; %20%20right:%200; %20%20bottom:%200; %20%20font-size:%2014px; } progress%20{ %20%20-webkit-appearance:%20none; %20%20-moz-appearance:%20none; %20%20appearance:%20none; %20%20position:%20absolute; %20%20width:%20100%; %20%20height:%20var(--progress-bar-height); %20%20background-color:%20var(--progress-bar-color); %20%20border:%20none; } progress::-moz-progress-bar%20{ %20%20background-color:%20var(--progress-bar-value-color); } progress::-webkit-progress-bar%20{ %20%20background-color:%20var(--progress-bar-color); } progress::-webkit-progress-value%20{ %20%20background-color:%20var(--progress-bar-value-color); } progress::-ms-fill%20{ %20%20background-color:%20var(--progress-bar-value-color); }
计算并显示百分比
$(document).ready(function()%20{ %20%20const%20win%20=%20$(window); %20%20const%20doc%20=%20$(document); %20%20const%20progressBar%20=%20$('progress'); %20%20const%20progressLabel%20=%20$('.progress-label'); %20%20const%20setValue%20=%20()%20=>%20win.scrollTop(); %20%20const%20setMax%20=%20()%20=>%20doc.height()%20-%20win.height(); %20%20const%20setPercent%20=%20()%20=>%20Math.round(win.scrollTop()%20/%20(doc.height()%20-%20win.height())%20*%20100); %20%20progressLabel.text(setPercent()%20+%20'%'); %20%20progressBar.attr({%20value:%20setValue(),%20max:%20setMax()%20}); %20%20doc.on('scroll',%20()%20=>%20{ %20%20%20%20progressLabel.text(setPercent()%20+%20'%'); %20%20%20%20progressBar.attr({%20value:%20setValue()%20}); %20%20}); %20%20win.on('resize',%20()%20=>%20{ %20%20%20%20progressLabel.text(setPercent()%20+%20'%'); %20%20%20%20progressBar.attr({%20value:%20setValue(),%20max:%20setMax()%20}); %20%20}) });
8.%20进阶:时间轴
时间轴相当于上述列表锚点的升级版,可用于年鉴展示、记事本、tudo%20list%20等应用中。
Timeline
1997
Lorem ipsum dolor sit amet, consectetur adipiscing elit
Nam non purus vel orci molestie consequat.
Etiam et velit in arcu consectetur aliquet et eu metus
Sed vitae diam rhoncus, imperdiet nunc quis, lacinia nulla.
Today
ol.timeline ol, ol.timeline, html, body { margin: 0; padding: 0; } *, *:before, *:after { box-sizing: border-box; } #wrapper { margin: 0 auto; max-width: 64em; } #container { float: left; padding: 1em; width: 100%; } h1, h2 { text-align: center; } ol.timeline, ol.timeline ol { list-style: none; } ol.timeline>li { padding-left: 2px; position: relative; } ol.timeline>li:before { background-color: #a2ed56; content: ""; height: 100%; left: 0; position: absolute; top: 0; width: 2px; } @media only screen and (min-width: 40em) { ol.timeline>li:before { left: 50%; transform: translateX(-50%); } } ol.timeline>li>h2 { background-color: #a2ed56; color: #1d1f20; margin: 0; position: -webkit-sticky; position: sticky; text-transform: uppercase; top: 0; } @media only screen and (min-width: 40em) { ol.timeline>li>h2 { border-radius: 0.25em; margin: 0 auto; margin-bottom: 1em; max-width: 200px; } } ol.timeline>li>ol { display: flex; flex-wrap: wrap; } ol.timeline>li>ol>li { border-top: 2px solid #a2ed56; flex: 0 0 100%; padding: 0 0 0.5em 1em; } @media only screen and (min-width: 40em) { ol.timeline>li>ol>li { flex-basis: 50%; } ol.timeline>li>ol>li:nth-child(odd) { padding-left: 0; padding-right: 1em; } ol.timeline>li>ol>li:nth-child(even) { margin-top: 2em; padding-right: 0; } } ol.timeline>li>ol>li>h3:first-child { color: #a2ed56; margin-bottom: -0.75em; } ol.timeline>li:nth-child(6n+2):before, ol.timeline>li:nth-child(6n+2)>h2 { background-color: #83e4e2; } ol.timeline>li:nth-child(6n+2)>ol>li { border-color: #83e4e2; } ol.timeline>li:nth-child(6n+2)>ol>li h3 { color: #83e4e2; } ol.timeline>li:nth-child(6n+3):before, ol.timeline>li:nth-child(6n+3)>h2 { background-color: #fd6470; } ol.timeline>li:nth-child(6n+3)>ol>li { border-color: #fd6470; } ol.timeline>li:nth-child(6n+3)>ol>li h3 { color: #fd6470; } ol.timeline>li:nth-child(6n+4):before, ol.timeline>li:nth-child(6n+4)>h2 { background-color: #fca858; } ol.timeline>li:nth-child(6n+4)>ol>li { border-color: #fca858; } ol.timeline>li:nth-child(6n+4)>ol>li h3 { color: #fca858; } ol.timeline>li:nth-child(6n+5):before, ol.timeline>li:nth-child(6n+5)>h2 { background-color: #fddc32; } ol.timeline>li:nth-child(6n+5)>ol>li { border-color: #fddc32; } ol.timeline>li:nth-child(6n+5)>ol>li h3 { color: #fddc32; } ol.timeline>li:nth-child(6n+6):before, ol.timeline>li:nth-child(6n+6)>h2 { background-color: #fafafa; } ol.timeline>li:nth-child(6n+6)>ol>li { border-color: #fafafa; } ol.timeline>li:nth-child(6n+6)>ol>li h3 { color: #fafafa; }
9. 进阶:文字堆积效果
A scroll (from the Old French escroe or escroue), also known as a roll, is a roll of papyrus, parchment, or paper containing writing.
Structure
A scroll is usually divided up into pages, which are sometimes separate sheets of papyrus or parchment glued together at the edges, or may be marked divisions of a continuous roll of writing material. The scroll is usually unrolled so that one page is exposed at a time, for writing or reading, with the remaining pages rolled up to the left and right of the visible page. It is unrolled from side to side, and the text is written in lines from the top to the bottom of the page. Depending on the language, the letters may be written left to right, right to left, or alternating in direction (boustrophedon).
Some scrolls are simply rolled up pages; others may have wooden rollers on each end: Torah scrolls have rather elaborate rollers befitting their ceremonial function.
History of scroll use
Scrolls were the first form of editable record keeping texts, used in Eastern Mediterranean ancient Egyptian civilizations. Parchment scrolls were used by the Israelites among others before the codex or bound book with parchment pages was invented by the Romans, which became popular around the 1st century AD. Scrolls were more highly regarded than codices until well into Roman times, where they were usually written in single latitudinal column.
The ink used in writing scrolls had to adhere to a surface that was rolled and unrolled, so special inks were developed. Even so, ink would slowly flake off of scrolls.
Rolls
Rolls recording UK Acts of Parliament held in the Parliamentary Archives, Palace of Westminster, London
html { margin: 0 auto; overflow: auto; position: relative; text-align: justify; font-size: 32px; background: #FDFC47; background: -webkit-linear-gradient(to right, #24FE41, #FDFC47); background: linear-gradient(to right, #24FE41, #FDFC47); } body { max-width: 500px; height: 500px; overflow: auto; color: #2D2D2D; margin: 40px auto; background: #FFFFFF; } body::after, *::before, span { position: sticky; top: 0em; bottom: 0em; white-space: nowrap; } p, h2, div { display: inline; font-size: 1rem; } h2::before { content: "§ "; } p::before { content: "¶ "; } h2 { color: rgba(255, 100, 100, 1); } b, i { color: rgba(255, 100, 100, 0.7); }
[].forEach.call(document.querySelectorAll("p,li,h2,a"), function (el) {
el.innerHTML = el.innerHTML
.split(" ")
.map(word => `${word}`)
.join(" ");
});
// 自动触发滚动
function autoscroll() {
document.scrollingElement.scrollBy({ top: 10, behavior: "smooth" });
}
var INTRVL = setInterval(autoscroll, 100);
function stop() {
clearInterval(INTRVL);
}
document.documentElement.addEventListener("mousemove", stop);
10. 进阶:拼图效果
.container { width: 470px; margin: 40px auto; background: #FFFFFF; height: 450px; overflow: auto; } svg { position: -webkit-sticky; position: sticky; top: 0; } path { fill: none; stroke: #2D2D2D; stroke-width: 1.5px; }
其他优秀案例
日历: https://codepen.io/dannievinther/details/pGdjPV
段落显示 https://codepen.io/BurmesePotato/pen/qBbqpNB
滑动卡片 https://codepen.io/Kseso/pen/JyEWoP
瀑布流 https://codepen.io/collinsworth/pen/aEJGvg
字幕式文章标题 https://codepen.io/coderthegreat/details/abzrOpg
鼠标滚轮控制元素 https://codepen.io/equinusocio/pen/GeBxJz
页面布局 https://codepen.io/havardob/details/gOPNpmm
页面布局 https://codepen.io/ncerminara/pen/VdLpzd
兼容性
如下图所示,当前并不是所有浏览器都支持 skicky 定位模式,不建议在大型应用中广泛使用,但是已经有 Stickfill 类似的 js垫片 使得未实现 sticky 定位的浏览器也得以支持,大家可尝试使用垫片,兼容更多的项目和浏览器 。
polyfill
Stickfill: https://github.com/wilddeer/stickyfill
到此这篇关于position:sticky 粘性定位的几种巧妙应用详解的文章就介绍到这了,更多相关position:sticky 粘性定位内容请搜索潘少俊衡以前的文章或继续浏览下面的相关文章,希望大家以后多多支持潘少俊衡!
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。
本文地址:/web/CSS/73095.html