position:sticky 粘性定位的几种巧妙应用详解

这篇文章主要介绍了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
FOOTER
 .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
FOOTER
 .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 就可实现页面滚动锚点固定效果,可用于实现通讯录滚动、日志记录滚动、其他分类列表滚动效果。

 
A
Apple
Artichoke
Aardvark
Ant
Acorn
D
Dog
Date
Danish
Dandelion

@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; 可以实现表格头部或某行固定,也可将多个表格合并到一起,当滚动到当前表格是,固定头部自动变为当前表格的表头。

 
NameAgeJobColorURL
Lorem.Ullam.Vel.At.Quis.
NameAgeJobColorURL
 .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. 进阶:页面进度条(优化)

优化版的进度条支持浏览进度百分比显示,助于提升用户体验。

 

Page Progress Bar Example

All images provided at random from Codepen assets. All ipsum text provided by officeipsum.com.

Face time level the playing field highlights. Bake it in quick win bench mark, or paddle on both sides. Re-inventing the wheel. What do you feel you would bring to the table if you were hired for this position drink from the firehose, but quarterly sales are at an all-time low or can you ballpark the cost per unit for me we are running out of runway.

Meeting assassin enough to wash your face so after I ran into Helen at a restaurant, I realized she was just office pretty good optics put a record on and see who dances, yet we're ahead of the curve on that one, or personal development. Bench mark beef up helicopter view highlights take five, punch the tree, and come back in here with a clear head, so translating our vision of having a market leading platfrom nor what's the status on the deliverables for eow?.

 :root { --progress-bar-height: 4px; --progress-bar-color: gainsboro; --progress-bar-value-color: dodgerblue; --progress-bar-value: 20%; } article { position: relative; padding: 24px; width: 100%; max-width: 700px; margin: 60px auto; } .article-title { position: sticky; top: 0; padding-bottom: 24px; } img { width: 100%; margin-bottom: 18px; } .progress-wrapper { position: relative; } .progress-label { position: absolute; right: 0; bottom: 0; font-size: 14px; } progress { -webkit-appearance: none; -moz-appearance: none; appearance: none; position: absolute; width: 100%; height: var(--progress-bar-height); background-color: var(--progress-bar-color); border: none; } progress::-moz-progress-bar { background-color: var(--progress-bar-value-color); } progress::-webkit-progress-bar { background-color: var(--progress-bar-color); } progress::-webkit-progress-value { background-color: var(--progress-bar-value-color); } progress::-ms-fill { background-color: var(--progress-bar-value-color); } 

计算并显示百分比

 $(document).ready(function() { const win = $(window); const doc = $(document); const progressBar = $('progress'); const progressLabel = $('.progress-label'); const setValue = () => win.scrollTop(); const setMax = () => doc.height() - win.height(); const setPercent = () => Math.round(win.scrollTop() / (doc.height() - win.height()) * 100); progressLabel.text(setPercent() + '%'); progressBar.attr({ value: setValue(), max: setMax() }); doc.on('scroll', () => { progressLabel.text(setPercent() + '%'); progressBar.attr({ value: setValue() }); }); win.on('resize', () => { progressLabel.text(setPercent() + '%'); progressBar.attr({ value: setValue(), max: setMax() }); }) }); 

8. 进阶:时间轴

时间轴相当于上述列表锚点的升级版,可用于年鉴展示、记事本、tudo list 等应用中。

 

Timeline

  1. 1997

    1. Lorem ipsum dolor sit amet, consectetur adipiscing elit

      Nam non purus vel orci molestie consequat.

    2. Etiam et velit in arcu consectetur aliquet et eu metus

      Sed vitae diam rhoncus, imperdiet nunc quis, lacinia nulla.

  2. 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 定位的浏览器也得以支持,大家可尝试使用垫片,兼容更多的项目和浏览器

以上就是position:sticky 粘性定位的几种巧妙应用详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS 教程