A few weeks ago, we were working on a table of contents for the Vanilla JS Academy. It’s a script that dynamically creates a list of skip links from the headings in a document. It was a great opportunity to implement the
:target pseudo-class, which is a neat CSS selector you might not know about.
As they explain in the MDN Web Docs:
:targetCSS pseudo-class represents a unique element (the target element) with an
idmatching the URL’s fragment.
- An example
- Browser support
- Learn more
Notice that I added a list of skip links above this heading.
When you click on one, your browser will scroll to that heading. The heading will be highlighted with a yellow background.
That’s because I have the following rule in my stylesheet:
:target pseudo-class is supported back to IE9. You can check out the compatibility data on Can I Use.
The following pages in the MDN Web Docs are helpful:
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!