Principle of the position-sticky effect
The definition in the official W3 documentation is: Sticky positioning is similar to relative positioning except the offsets are automatically calculated in reference to the nearest scrollport.
Translation: Sticky positioning can show the combination of “relative” and “fixed”, which is “relative” under normal circumstances, but when the scroll bar of the sticky element’s parent (the nearest scrollport) appears, The sticky element will be represented as fixed when it is from the set position such as (top: 0), which is relative to the fixed of the nearest scrollport.
One of the most important concepts is nearest ScrollPort, which means that the sticky element will be located relative to its nearest scrollport before it disappears.
Normal use
div.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
background-color: yellow;
padding: 50px;
font-size: 20px;
}
Copy the code
A scroll bar appears in the whole webpage, and nearest Scrollport is the body of the webpage, so when the scroll bar appears, the contents with yellow background will be positioned at top: 0 relative to the webpage
Codepen address codepen. IO/yy88xu/pen /…
overflow:visible
The parent element cannot have anyoverflow:visible
Overflow Settings outside, otherwise no sticky effect.
I didn’t know what this meant, so INSTEAD I set overflow: Auto to see what would happen. IO /yy88xu/pen/…
.big-wrap{
max-height: 500px;
border: 1px solid black;
overflow: auto; /* go against the grain */
}
.nav{
position: -webkit-sticky;
position: sticky;
top: 0px;
padding: 10px;
background: yellow;
}
Copy the code
Nearest ScrollPort to.nav is a. Big-wrap container, so when a scroll bar appears in the. Big-wrap container, the. Nav element can be fixed inside the. Big-wrap container. 0px; The location of the.
So many articles say that “parent elements cannot have any overflow Settings other than overflow: Visible, otherwise there will be no sticky effects.” Is unreasonable! The parent element set Overflow: Auto or Overflow: Scroll sticky effect still exists, but nearest Scrollport is not the page (the entire screen), but the parent element itself.
discuss
If position: sticky triggers sticky effect, it will not work. If so, welcome to comment and discuss, let’s learn and explore together.
Useful url for inspiration
Good use case sets: segmentfault.com/a/119000003… To explore the position – sticky failure problem: www.cnblogs.com/coco1s/p/14… Developer:developer.mozilla.org/en-US/docs/…