Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use position:sticky

Shulou Source: shulou.com Published: 2022-06-02 14:54:48 09月27日 Update

In this issue, the editor will bring you about how to use position:sticky. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

While studying the rem layout, I accidentally saw that the navigation bar on the home page of NetEase News Mobile used a CSS 3 attribute sticky positioning position:sticky.

It is a mixture of relative positioning position:relative and fixed positioning position:fixed.

Using it, we no longer need to listen to scroll events, we can achieve the effect of absolute positioning of the navigation bar scrolling.

Basic usage

Nav {position:sticky; top:10px; / * threshold * /}

Top/bottom attribute

For example, when we set up top:100px, before the viewport viewport scrolls to the element distance less than the set top:100px, the element is relatively positioned. When you scroll to top:100px, the element is fixed at a distance from the top to the top:100px until the viewport viewport rolls back below the threshold.

According to the following example, we can see that the top value set by the position:sticky element is the distance from the viewport, and when it scrolls below its value, it is fixed in the viewport, and the effect of the element is fixed positioning.

The structure of the following example:

< h2 >

The top high 200px red line is the middle line.

< /h2>

< nav >

This is the navigation top:100px.

< /nav>

< p>

Get out.

< /p>

< p>

Get out.

< /p>

Effective condition

It is important to note that there are several necessary conditions for using this property, otherwise it will become invalid:

Parent elements cannot have overflow:hidden or overflow:auto attributes.

You must specify one of the values of top, bottom, left, and right4, otherwise it will only be in a relative position.

The height of the parent element cannot be lower than the height of the sticky element.

The sticky element takes effect only within its parent element.

Compatibility situation

Position:-webkit-sticky;position: sticky

This is how to use the position:sticky shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Tags: Elements positioning attributes viewports navigation examples content effects conditions threshold top height analysis necessary necessary professional small and medium midline event location Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi vpn Shulou Information MariaDB Apple