position: sticky
anchors to the nearest scrollable ancestor, and unfortunately, CSS doesn't currently provide a way to override that behavior or explicitly set which scroll context a sticky element should use.
In your example, once .subtable
has overflow-y: auto
, it becomes the scroll container for its children. That means any sticky element inside it will stick relative to .subtable
, not .main
, even if .main
is the scroll context you want.
There’s no native CSS way to “skip” a scroll container and anchor stickiness to a higher-level ancestor. Sticky positioning is strictly scoped to the first scrollable ancestor with a defined height and overflow.
Workarounds
Here are a few approaches developers use to work around this limitation:
Avoid nested scroll containers If you can restructure your layout so that .main
is the only scrollable ancestor, sticky behavior will work as expected across all nested elements.
Move sticky elements outside the scrollable container You can place the sticky cell outside .subtable
and use CSS or JavaScript to visually align it. This keeps it anchored to .main
, but may require layout adjustments.
Simulate sticky behavior with JavaScript You can listen to scroll events on .main
and manually adjust the position of the nested sticky cell. This gives you full control over scroll context, though it’s more complex and less performant than native sticky positioning.
Helpful References
Troubleshooting CSS sticky positioning – LogRocket
CSS Tricks: Dealing with overflow and position: sticky
Cheers
Jeffrey