I'm facing a challenge with my website where I have a fixed top-of-page header and I want the sub-headers in the content to be sticky. I've tried two different approaches using CSS, but unfortunately, neither of them is working as expected:
The first approach involves using
position: fixed
orposition: sticky
for the page header. This causes the rest of the page to scroll underneath the header, making the sub-headers invisible when they stick. They end up sticking to the top of the page instead of their own visible section. To fix this, I could set thetop
value to equal the height of the header, but this solution is not ideal as the header's height may vary.Another drawback of this method is that the page scrollbar intrudes into the header area rather than being confined to the scrolling section.
The second approach involves using flex or grid to divide the page vertically into two sections - the header and a scrollable main section. While this does make the sub-headers stick correctly to the main section, it brings about other issues. Anchor links with
#fragments
no longer function reliably due to being inside a nested scrolling block. Additionally, there are significant bugs in mobile Safari where focusing on text input fields leads to the entire page scrolling instead of just the main section. The page becomes stuck, requiring a reload to resolve the issue. Here is someone else's report on this Safari bug and you can view their video showing the problem. (This bug can occur even without the nested scrolling div, but it exacerbates the situation.)
Finding a solution where the main header remains fixed while allowing the sub-headers to stick seems to be a common dilemma for many websites. Upon examining popular mobile sites like Google Docs, reddit, StackOverflow, and MDN, I noticed they opt for the first method mentioned above and sacrifice sticky sub-headers.
Any suggestions on achieving sticky sub-headers without resorting to creating a nested scrolling block? Or perhaps a workaround for Safari's scrolling flaw?