如何使用 CSS 使元素保持不变 position: sticky

简介

您可能在过去将csspostion属性与relativeAbsisite值一起使用过。现代网络浏览器现在支持ticky值。它允许您在滚动到某个点时使元素保持不变。

带有Position:Sticky的元素将表现为相对定位的元素,直到到达指定点,然后开始表现为静态定位的元素。

在本文中,您将创建一个使用Position:Sticky的示例,以了解它的行为和功能。

预约

如果您想继续阅读本文,您将需要:

使用position:sticky

考虑一个将成为flex容器的div容器。其中嵌套了4个附加的‘div’元素,它们将成为flex项。这4个div元素将包含Shark-1Shark-2Shark-3Shark-4的图片。

在代码编辑器中,使用以下标记:

 1<div class="container">
 2  <div class="item shark-1">
 3    <img
 4      src="/images/punk.png"
 5      width="100"
 6      alt="Sammy the Shark with a punk theme."
 7    >
 8  </div>
 9  <div class="item shark-2">
10    <img
11      src="/images/pony.png"
12      width="100"
13      alt="Sammy the Shark with a magical pony theme."
14    >
15  </div>
16  <div class="item shark-3">
17    <img
18      src="/images/dino.png"
19      width="100"
20      alt="Sammy the Shark with a dinosaur theme."
21    >
22  </div>
23  <div class="item shark-4">
24    <img
25      src="/images/steampunk.png"
26      width="100"
27      alt="Sammy the Shark with a steampunk theme."
28    >
29  </div>
30</div>

并添加以下样式:

 1.container {
 2  display: flex;
 3  justify-content: space-around;
 4  align-items: flex-start;
 5  border: 2px dashed rgba(114, 186, 94, 0.35);
 6  height: 400px;
 7  background: rgba(114, 186, 94, 0.05);
 8}
 9
10.shark-1 {
11  position: sticky;
12  top: 0;
13}
14
15.shark-2 {
16  position: sticky;
17  top: 4rem;
18}
19
20.shark-3 {
21  position: sticky;
22  bottom: 1rem;
23  align-self: flex-end;
24}

在这个例子中,flex容器上的stretch-items:flex-start规则很重要,因为否则flex项目默认值为stretch,其中元素将占据容器的整个高度,取消粘性效果。

<$>[注] 注意: 如果您想了解不同的flexbox属性和值,请查看我们的flexbox primer。 <$>

保存此文件并在现代Web浏览器中打开它:

Sammy the Shark with a punk theme.
Sammy the Shark with a magical pony theme.
Sammy the Shark with a dinosaur theme.
Sammy the Shark with a steampunk theme.

向上和向下滚动,观察`粘滞‘行为。请注意,粘滞定位的元素只在其父元素内粘滞。

<$>[警告] 警告: 有两种常见的情况,Position:Sticky元素不会按照预期粘在窗口上:

没有定义inset属性:请确保粘性元素设置了topbottom。或者,如果是水平滚动,则为leftright

元素的上级之一具有不兼容的overflow:如果粘性元素的任何父级或上级将overflow设置为iddenscllauto。这同样适用于overflow-xoverflow-y。 <$>

第一条和第二条鲨鱼相对于由视区建立的包含块的_top_是粘性的。第三条鲨鱼相对于由视区建立的包含块的_Bottom_是粘性的。第四条鲨鱼不会滚动到粘滞的位置,因为它没有被分配‘位置:粘滞’。

结论

在本文中,您创建了一个使用Position:Sticky来理解它的行为和功能的示例。

截至2020年,95%的浏览器对位置:粘滞‘有一定程度的支持。详情请参考[是否可以使用css位置:粘滞](https://caniuse.com/css-sticky).旧版本的Safari将需要-webkit`供应商前缀。在将此功能整合到您的Web应用程序之前,请确保您的目标受众可以使用此功能。

如果您想了解更多关于css的内容,请查看我们的css主题页面获取练习和编程项目。

Published At
Categories with 技术
Tagged with
comments powered by Disqus