Just found out about a super cool and often overlooked CSS link pseudo-class.
I am referring to the:target
pseudo-class. What it does is to indicate which element is clicked and navigated to via using internal hashtag links (the links that have a format like <a href="#insert-id-here">
).
Let's take the following HTML:
<div id='section-1'>
<h1>Section one</h1>
<a href='#section-2'>Go to section two</a>
</div>
<div id='section-2'>
<h1>Section two</h1>
<a href='#section-1'>Go to back to section one</a>
</div>
For example, we can use the :target
pseudo element to say that if someone clicks on a link with href='#section-2'
then the #section-2
element will get some CSS properties:
#section-2:target {
background-color: lightgreen;
}
The lightgreen
background will become active ONLY IF someone clicks on a link. So, if we just scroll to that link we will see the below output:
But if you scroll back up and click the button, it will move to the section and activate the lightgreen
background:
Checkout the below codepen:
See the Pen
attr() by JS Craft (@js-craft)
on CodePen.
You can also see here how to use the focus-within pseudo class to build a pure CSS multi level dropdown menu.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.