谈谈CSS新特性position:sticky的使用

单词sticky的中文意思是“粘性的”,当然他的特性也很符合他的名字。我们一般常用的position属性无非就是relative(相对定位)、absolute(绝对定位)、fixed(固定定位)。

  • relative:生成相对定位的元素,相对于其正常位置进行定位。
  • absolute:生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。
  • fixed:生成绝对定位的元素,相对于浏览器窗口进行定位。

而sticky可以看成是position:relativeposition:fixed的结合体——当元素在屏幕内,表现为relative,就要滚出显示器屏幕的时候,表现为fixed。效果 请看这里

HTML结构如下:

<article>
    <div class="category">Category Header</div>
    <h1 class="title">Article 1 Title</h1>
    <p>Body content would go here.</p>
    <!-- More Content -->
    <div class="footer">
        <p>Article 1 Footer</p>
    </div>
</article>

<article>
    <div class="category">Category Header</div>
    <h1 class="title">Article 2 Title</h1>
    <p>Body content would go here.</p>
    <!-- More Content -->
    <div class="footer">
        <p>Article 2 Footer</p>
    </div>
</article>

上面包含了两篇article,文章中包含一个Header、Title、content和footer。

CSS部分如下:

.category,.title,.footer {
    position: -webkit-sticky; /* Required for Safari */
    position: sticky;
    height: 50px;
}

.category {
    top: 0;
}

.title {
    top: 0;
    background: green;
    margin: 0;
}

.footer {
    bottom: 100px;
    z-index: -1;
}
article {
    background-image: linear-gradient(
        to bottom,
        transparent 50px,
        #F5A623 50px,
        #F5A623 calc(100% - 50px),
        transparent 0
    );
    margin: auto auto 50px auto;
}

一、首先设置Header、Title和footer的定位为sticky,目前对于Safari浏览器需要使用-weikit-前缀做兼容处理

position: -webkit-sticky; /* Required for Safari */
position: sticky;

二、然后设置粘贴位置,是要注意以下几点

  1. 须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
  2. top和bottom同时设置时,top生效的优先级高,left和right同时设置时,left的优先级高。
  3. 设定为position:sticky元素的任意父节点的 overflow 属性必须是 visible,否则position:sticky不会生效
  4. 达到设定的阀值。也就是设定了position:sticky的元素表现为relative还是fixed是根据元素是否达到设定了的阈值决定的
  5. 父级元素也不能设置固定的height高度值,否则也没有粘滞效果(2019-05-22新增)
top: 0;

这里我们可以看到设置粘贴位置为顶部。

三、效果优化

为了达到案例中的效果,需要对article的属性进行一些设置

article {
    background-image: linear-gradient(
        to bottom,
        transparent 50px,
        #F5A623 50px,
        #F5A623 calc(100% - 50px),
        transparent 0
    );
    margin: auto auto 50px auto;
}

这里运用到了CSS3的线性渐变新特性,to bottom表示方向从上至下,transparent 50px表示前50px的区域使用透明色,calc(100% - 50px)这里的calc样式CSS3的一个新属性,可以用它来动态的计算宽高。

四、实际运用

在实际中我们可以在很多的地方用到它,我在我的个人博客中就是用到了这个特性,点击查看

后续我会在我的个人博客网站中使用更多的新特性,感兴趣的可以持续关注

发布了64 篇原创文章 · 获赞 45 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/DengZY926/article/details/102502028
今日推荐