CSS :target
The :target pseudo-class in CSS allows you to style an element that is currently being targeted by a fragment identifier in the URL. This is particularly useful for single-page applications or navigation menus that scroll to different sections of the page. When an element is targeted, it can change its appearance based on this selector.
In this tutorial, we'll use fictional data to illustrate how :target works and how to implement it in HTML and CSS.
<h2 id="section1">Section 1</h2>
<p>This is some content for Section 1. Click the link below to see the styling change.</p>
<a href="#section2">Go to Section 2</a>
<h2 id="section2">Section 2</h2>
<p>This is some content for Section 2. Click the link below to see the styling change.</p>
<a href="#section3">Go to Section 3</a>
<h2 id="section3">Section 3</h2>
<p>This is some content for Section 3. Click the link below to return to Section 1.</p>
<a href="#section1">Go to Section 1</a>
<style>
h2 {
transition: background 0.3s ease;
}
h2:target {
background: yellow;
}
</style>
In the example above:
- We have three sections: Section 1, Section 2, and Section 3.
- Each section has a corresponding link that targets another section using its
id. - When you click the link to a section, it activates the
:targetpseudo-class for that section'sh2, changing its background color to yellow.
Experiment with the links to see how the :target pseudo-class works in action!