The :target
pseudo-class is applied to the target element, in other words, to the identifier that is specified in the browser's address bar.
element:target {
property: value;
}
The :target pseudo-class in CSS is a powerful selector that allows you to style elements based on the current URL fragment. Here's an overview of how it works and how to use it:
#section1:target {
background-color: yellow;
}
This would apply a yellow background to the element with id="section1" when it's targeted in the URL.
Use cases for :target
Highlighting sections: Highlight the current section of a page when linked to directly.
Creating interactive elements: Show/hide content without JavaScript.
Building navigation systems: Create tab-like interfaces or slide-out navigation drawers.
Implementing modals: Create CSS-only modal windows.
<a href="#content">Show Content</a>
<div id="content">
<p>This content is initially hidden.</p>
<a href="#">Hide Content</a>
</div>
#content {
display: none;
}
#content:target {
display: block;
}
In this example, clicking "Show Content" will reveal the hidden div, while clicking "Hide Content" will hide it again. The :target pseudo-class provides a powerful way to create interactive elements and enhance user experience using only CSS. While it has some limitations, it can be an excellent tool for creating simple interactions without relying on JavaScript.