DEV Community

Discussion on: Offsetting named anchor and scrollIntoView position.

Collapse
 
lobo_tuerto profile image
Víctor Adrián

What happens when you aren't able to easily change the anchors, or the content they point to?

For example for sites written in Markdown, you can get an autogenerated TOC that directly links to the headers.


What I found was a very easy and cool hack. By applying some styling to the header elements you can achieve the desired effect.

Just apply a padding, then subtract the same quantity as a negative margin.

If you want to see it in action, have a look at this: lobotuerto.com/blog/vuejs-componen...

Click around using the TOC or the § symbols besides the headers.

Code is more or less like this:

h1::before, h2::before, h3::before
  content: ''
  display: block
  margin-top: -80px
  padding-top: 80px