CSS :target Selector with Examples
The :target selector is a pseudo-class in CSS selecting the element that is the target element of the referring URI. In other words, this pseudo-class selects the element being targeted by a fragment identifier in the URL.
A fragment identifier is the part of the URL after hash symbol (#) which is used to directly link to a specific part of the web page, such as a heading or section.
The CSS :target selector come into play when you want to navigate to a specific section of a webpage through an anchor link. It provides a powerful styling options to enhance user experience and visual cues. It highlights the selected or active section when a user navigates to it via a URL fragment.
Basic Syntax to Define CSS :target Selector
The :target selector is used to style an element that matches the fragment identifier in the URL. The general syntax to use :target selector is as follows:
:target {
/* CSS Styles to apply to the targeted element */
}
Basic Examples
Let’s take an example in which you will click a link to navigate to a specific section, that section will be highlighted.
Example 1:
<!DOCTYPE html>
<html>
<head>
<style>
:target {
background-color: red;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<a href="#section1">Go to Section 1</a>
<a href="#section2">Go to Section 2</a>
<h2 id="section1">Section 1</h2>
<p>Content of Section 1...</p>
<h2 id="section2">Section 2</h2>
<p>Content of Section 2...</p>
</body>
</html>
In this example, when you click a link to #section1, Section 1 will have a red background, indicating it’s the targeted section.
Output:
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
:target {
outline: 2px solid red;
padding: 5px;
}
</style>
</head>
<body>
<a href="#info">More Info</a>
<div id="info">
<h3>Information Section</h3>
<p>Details about the topic...</p>
</div>
</body>
</html>
In this example, when you will click on the “More Info” link, the page smoothly scrolls to the targeted section, and the section gets an outline.
Let’s take an example in which we will build a simple tabbed interface using :target selector.
Example 3:
<!DOCTYPE html>
<html>
<head>
<style>
.tab-content {
/* Hide all content by default */
display: none;
}
:target {
/* Show only the targeted content */
display: block;
}
</style>
</head>
<body>
<div class="tabs">
<a href="#tab1">Tab 1</a>
<a href="#tab2">Tab 2</a>
<a href="#tab3">Tab 3</a>
</div>
<div id="tab1" class="tab-content">Content for Tab 1...</div>
<div id="tab2" class="tab-content">Content for Tab 2...</div>
<div id="tab3" class="tab-content">Content for Tab 3...</div>
</body>
</html>
When you will click on a tab link, only the corresponding content section will be visible.