:target

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.

Syntax



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:

What is the :target pseudo-class?

The :target pseudo-class selects an element whose id matches the URL's fragment identifier (the part after the # symbol). For example, if the URL is "example.com#section1", the element with id="section1" would be selected by :target. How to use :target To use the :target pseudo-class, simply add it to your CSS selector:

#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.

Advantages of using :target

No JavaScript required: Allows for simple interactivity using only CSS. SEO-friendly: Works well with URL-based navigation, which search engines can easily crawl. Accessibility: Provides a native way to handle focus and navigation.

Considerations when using :target

URL changes: Using :target affects the URL, which impacts browser history. Page jumps: Can cause unwanted scrolling when the target element is not in view. Single target: Only one element can be targeted at a time. Browser support: While generally well-supported, always check compatibility for older browsers. Example: Toggle content visibility Here's a simple example of using :target to show/hide content:

<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.