9

CSS实现滚动高度自动变小的粘滞效果

 2 years ago
source link: https://www.zhangxinxu.com/wordpress/2022/04/css-sticky-size-change/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CSS实现滚动高度自动变小的粘滞效果

这篇文章发布于 2022年04月22日,星期五,14:28,归类于 CSS相关。 阅读 937 次, 今日 195 次 一条评论

by zhangxinxu from https://www.zhangxinxu.com/wordpress/?p=10316 鑫空间-鑫生活
本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可以联系授权。

猫与花

一、先看下效果

如下 MP4 视频示意(不动点击播放),可以看到默认页面的 header 头部元素高度挺高的,随着滚动的进行,头部固定定位了,同时高度也变小了,减小对页面高度的占用。

眼见为实,您可以狠狠地点击这里:头部标题导航高度自动伸缩demo

如何实现的呢?

二、双 Sticky 粘性定位

需要悬浮固定的元素内外两层嵌套,假设如下HTML代码:

<header>
    <header-inner>
        ...
    </header-inner>
</header>

则核心的 CSS 是这样的:

header {
    --height-outer: 120px;
    --height-inner: 60px;
    /* by zhangxinxu */
    display: flex;
    align-items: center;
    position: sticky;
    height: var(--height-outer);
    top: calc(var(--height-inner) - var(--height-outer));
}
header-inner {
    display: flex;
    line-height: var(--height-inner);
    position: sticky;
    top: 0; 
}

就可以实现这个实用的小交互效果了。

具体实现描述如下:

外层元素粘性定位,设置 top 属性值为负的内外高度的差值,内层元素也是粘性定位,设置 top 属性值为 0,保证吸顶效果。

学会了么?

赶快在自己的项目中使用吧。

1f618.svg

(本篇完)1f44d.svg 是不是学到了很多?可以分享到微信
1f44a.svg 有话要说?点击这里

本文为原创文章,欢迎分享,勿全文转载,如果实在喜欢,可收藏,永不过期,且会及时更新知识点及修正错误,阅读体验也更好。
本文地址:https://www.zhangxinxu.com/wordpress/?p=10316


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK