Home > Article > Web Front-end > Why Isn't 'position: sticky' Working With a Defined Element Height?
Understanding Sticky Positioning
Sticky positioning, as defined by CSS, operates within a flow root (typically the browser viewport or a scrollable container) and enables elements to remain fixed relative to their surroundings until certain conditions are met. When an element encounters the specified threshold (e.g., a top offset from the viewport), it becomes "stuck" in place until it reaches the opposite edge of its containing block.
Overflow Affecting Sticky Functionality
In the given scenario, where 'position: sticky' is applied to an element, but the behavior is not as expected, it's essential to consider the element's containing block and any overflow that may be present.
Element and Containing Block Relationship
In the code provided, the element with 'position: sticky' (#footerNav) has its containing block set as 'html, body'. As the CSS defines 'html, body { height: 100% }', the entire viewport becomes the containing block.
Overflow Issue
However, since the #main div has a 'height: 92%' property, while the #footerNav has a 'height: 8%', the content overflows beyond the combined 'height' values. This overflow creates an extended containing block, allowing the sticky element to reach the opposite edge prematurely (i.e., at the bottom of #main). As a result, the sticky element appears fixed at the end of #main instead of remaining stuck until it reaches the bottom of the browser window.
Solution
To resolve the issue, one can remove the height restrictions on the #main element, allowing the content to overflow naturally. This ensures that the scroll container remains the entire viewport, and the sticky element functions as expected, remaining stuck until it reaches the actual bottom of the page.
The above is the detailed content of Why Isn't 'position: sticky' Working With a Defined Element Height?. For more information, please follow other related articles on the PHP Chinese website!