:target CSS Pseudo Class
Description
The :target pseudo-class in CSS is a powerful selector used to style an element that matches the fragment identifier in the current URL. Essentially, when a URL contains a hash (e.g., #section1), the element with the corresponding id becomes the target, and styles defined with :target are applied to it. This makes it particularly useful for creating interactive experiences without relying on JavaScript, such as highlighting the currently visible section, building tab-like interfaces, or implementing simple scroll-to-section effects.
One of the key advantages of :target is its dynamic nature. Unlike static classes, the pseudo-class automatically responds to URL changes. For example, navigating to example.com/page#about would apply the :target styles to the element <div id="about">. This allows designers to provide visual feedback, such as changing background colors, borders, or visibility, to indicate which section is currently active.
When using :target, it’s common to combine it with CSS properties like display, background-color, or opacity to create effects like showing or hiding content. Additionally, it pairs well with elements such as a for navigation links that point to specific sections of a page. However, it only works for elements with an id attribute matching the URL fragment and does not apply if the fragment does not exist or is removed.
Example Usage:
<nav>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
</nav>
<div id="section1" class="content">
<p>Content of Section 1</p>
</div>
<div id="section2" class="content">
<p>Content of Section 2</p>
</div>
.content {
display: none;
padding: 20px;
border: 1px solid #ccc;
}
.content:target {
display: block;
background-color: #f0f8ff;
}
In this example, only the section corresponding to the fragment identifier in the URL is displayed, while other sections remain hidden. This technique is frequently used for simple tab interfaces, FAQs, or single-page navigation where each link targets a specific part of the page.
Another helpful use case is adding visual emphasis to a section without changing the layout. For example, you could use outline or transform with :target to highlight the element in a subtle, non-intrusive way. This makes :target a versatile tool for enhancing user experience on static web pages.
Syntax
:target {
/* ... */
}
Example
Browser Support
The following information will show you the current browser support for the CSS :target pseudo class. Hover over a browser icon to see the version that first introduced support for this CSS psuedo class.
This psuedo class is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 31st December 2025
