CSS implements a sticky effect that automatically reduces the scroll height

by zhangxinxu from https://www.zhangxinxu.com/wordpress/?p=10316 Xin Space-Xin Life

This article welcomes sharing and aggregation. There is no need to reprint the full text. The copyright is respected. The circle is so large. If you need it urgently, you can contact for authorization.

cat and flower

First, look at the effect

As shown in the following MP4 video (click to play without moving), you can see that the height of the header element of the default page is quite high. As the scrolling progresses, the header is fixed and positioned, and the height is also smaller, reducing the height of the page. occupancy.

Seeing is believing, you can hit hard here: Header header navigation height auto-scaling demo

How to achieve it?

2. Double Sticky Sticky Positioning

The elements that need to be suspended and fixed need to be nested inside and outside two layers, assuming the following HTML code:

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

Then the core CSS looks like this:

 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;  }

This practical small interaction effect can be achieved.

The specific implementation is described as follows:

For the sticky positioning of the outer element, set the top attribute value to be the negative difference between the inner and outer heights. The inner element is also sticky positioned. Set the top attribute value to 0 to ensure the ceiling suction effect.

Did you learn it?

Quickly use it in your own projects.

1f618.svg

This article is an original article, welcome to share, do not reprint in full text, if you really like it, you can collect it, it will never expire, and will update knowledge points and correct errors in time, and the reading experience will be better.

Address of this article: https://www.zhangxinxu.com/wordpress/?p=10316

(End of this article)

This article is reprinted from: https://www.zhangxinxu.com/wordpress/2022/04/css-sticky-size-change/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment