introduce

position: sticky; Sticky positioning, based on the user’s scrolling position.

Principle:

Set as a sticky-positioned element that depends on the user’s scrolling, positon: relative; Switch between position: Fixed and position.

It behaves like positon: relative; ;

And when the page scrolls beyond the target area, it will appear as position: fixed, fixed to the target position.

The target region here means that the element has a specific threshold relative to its parent by specifying top, right, bottom, or left,

At the same time, the sticky attribute takes effect only when one (or more) of the four thresholds is specified.

grammar


div .sticky {
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 0;
}

Copy the code

Note:

The sticky attribute is not very compatible and Safari needs to use -webkit-prefix.

Application scenarios

Page side navigation, click to automatically locate to the target area in the article, navigation is always fixed on the right side of the page.