Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Using the CSS link :target pseudo-class to style elements

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.

Home Screencasts Best of Newsletter Search X