I’m having trouble setting the scroll offset on my page with my sticky navbar. I thought that normally, when the navbar is fixed, the offset is set to the height of the navbar automatically (correct me if I’m wrong) but since I’m using “position:sticky” it doesn’t work anymore.
To be more specific: I need to link to some H3-headings on my site and the content will always be hidden behind by sticky navbar. The only solution I could think of is setting a margin-top to my headings, but that wouldn’t look good… So I was hoping there is another way to solve this.
You say it yourself: offset is for fixed navbar, and your navbar isn’t fixed, it’s sticky. So you can’t benefit from the offset. I’m finding myself in this situation often lately too.
You’ve got to be creative and craft your offset manually in another way. For example by using another element than your section to define the ID.
Here is an example where I’m using a dummy div, positionned absolute on top left of the section, with a manual offset set on the magin top, of exactly the height of the navbar. So in my case the navbar is 60px so the offset is margin top -60px. I colored the div so you can see it, but once you have it working, you can make it invisible and/or shrink it to 1px.
thanks for your help! Since my problem wasn’t with the sections (which have enough padding for the non-existent scroll offset) but with the headings, I actually just put a negative margin to my headings and enlarged the padding so they still looked the same. Now my anchor links scroll to the correct position.
I just hope there is no disadvantage in the negative margin because the headings are invisibly positioned behind the content above now, but at the moment I can’t think of a reason why this is a bad idea.
But maybe there is another solution with JS after all with which I could manipulate the scroll offset of the page without this little CSS hack?
Thanks again for your opinion! I tested all anchor links and other interactive elements on my page and (mostly) everything still works perfectly well. So I’m sticking to this solution!
The only thing I had to fix: I’m using h3 elements as a trigger in my accordion element (as you can see on the bottom of the page - but I think interactions aren’t working in the preview, at least I’m not able to see them correctly). I had to give those headings an extra class with “normal” padding/margin because if I was clicking on one of them the element underneath was opening. So that is a little detail you need to consider using negative margins.
Oh I forgot to test for IX triggers. IX can steal the focus easily so it’s not always very evident to mix click IX triggers with Links when there’s overlapp.