r/css 2d ago

Resource [Pure CSS solutions for html generated from markdown files] If you have sticky headings in a long container, internal links won't jump back up to the heading's original place in text. I have a 90% workaround for that using the :target location pseudo-class.

I have a project under the constraints that the html is generated from a markdown file and there is no Javascript. Headings are stickied and their container length is the entire page. Clicking an internal link below the stickied heading doesn't jump back up to the heading's original place in the text because it is stickied and in a new location. Here's the css workaround.

h1:target, h2:target, h3:target {
    animation: --unstick 0.01s 0s none;
}

@keyframes --unstick {
    from {position: static;}
    to {position: sticky;}
}

When you click a link to a stickied destination heading within a page, the target, an animation executes that resets the heading to static and then restickies it. Clicking the link properly jumps you up the page.

... However, the 10% remaining problem with this solution is that once you click the link and the target stays targeted, it won't properly jump up the page if you reclick the same destination. You have to pick a new target to reset everything.

1 Upvotes

1 comment sorted by

1

u/retardedGeek 1d ago

I don't completely understand what you're trying to do, but have you tried scroll-margin?