4

what is

Viscous positioning position sticky element using normal document flow layout ( static ), when its border ( border rectangle phase) to latest rolling ancestor the borders (i.e. Content rectangular is less than the specified threshold), the position sticky The element is fixed nearest scroll ancestor element

how to use

To achieve tack positioned addition to specifying position: sticky; needed outside the specified threshold, i.e., the horizontal scroll must specify left/right , vertical scrolling must be specified top/bottom .
like:

.some-component{
    position: sticky;
    top: 0px;
}

Sticky positioning position sticky can be used to achieve some "ceiling" effects

Advanced

How is the threshold calculated?

image
for example:

.sticky-btn{
    position: sticky;
    top: 10px;
}

It means that .sticky-btn border of the 061eaa04edc907 element and the upper inner border of the scrolling container (that is, the content rectangle ) edge is less than 10px , the element is in a fixed position.

Multiple sticky elements

  1. There can be multiple valid sticky elements sticky elements are independent of each other;
  2. sticky element is a positioning element. When multiple sticky elements overlap, the overlapping principle of positioning elements is followed.

other

  1. The invalid sticky element behaves the same as the relative location.

Invalid sticky element

When I use position: sticky; first time, I always find that the effect is not achieved. The common reasons are:

  1. left/right is specified when scrolling horizontally;
  2. Vertical scrolling is checking if top/bottom is specified;
  3. sticky an element's parent (or ancestor) specifies overflow/overflow-x/overflow-y property, and the value is hidden/scroll/auto ;
  4. sticky The parent element (not the ancestor element) of the element is not yet visible in the scroll element viewport.
    You can see this demo

compatibility

Can I Use CSS position: sticky

As of 2020, 95% of browsers have some level of support for position: sticky
Older versions of Safari will require the -webkit vendor-prefix

Usually written like this:

position: -webkit-sticky;
position: sticky;

Downgrade scheme (polyfill)

If you have to be compatible with various browsers, you have to use JS to achieve it. Fortunately, there are already many excellent libraries:

  1. react-sticky
  2. Stickybits

refer to

Organized from GitHub notes: parsing position: sticky; .

Buy me a coffee ☕


普拉斯强
2.7k 声望53 粉丝

Coder