The CSS Positioned Layout Module defines sticky positioning as a method where the offset of a box is calculated relative to the nearest ancestor with a "scrolling box" or the viewport. However, the exact nature of scrolling boxes has sparked some confusion.
A scrolling box is essentially a box where the overflow property is set to a value other than visible. Setting overflow to hidden, for example, creates a box with scrollable content.
In the context of sticky positioning, the nearest scrolling box to a sticky element plays a crucial role. If an ancestor of the sticky element has its overflow set to a scrolling value, the sticky element's offset will be calculated relative to that scrolling box.
To control whether a box becomes a scrolling box, one needs to set the overflow property accordingly. Setting overflow to visible prevents the creation of a scrolling box, while setting it to auto, scroll, or hidden creates a scrolling box.
Consider the following example:
.wrapper { height: 200vh; border: 2px solid; } .wrapper > div { position: sticky; top: 0; height: 20px; background: red; }
<div class="wrapper"> <div></div> </div>
This code creates a tall container (wrapper) and a sticky element (div) inside it. The wrapper has overflow: hidden, making it a scrolling box. When the user scrolls the page, the sticky element will stick to the top of the viewport until it reaches the top of the wrapper. At this point, the sticky element will stop scrolling because it has reached the top of its nearest scrolling box, the wrapper.
The above is the detailed content of How Do Scrolling Boxes Influence Sticky Positioning in CSS?. For more information, please follow other related articles on the PHP Chinese website!