:target CSS Pseudo Class

Description

The CSS :target pseudo-class is used to style the element that is the target of the current document URL. This can be useful for highlighting or otherwise styling a specific section of a page that a user has linked to, such as a table of contents entry or a specific heading.

To use the :target pseudo-class, simply add it to the end of a selector for the element that you want to style. For example, to style an element with the ID my-element when it is the target of the current document URL, you would use the following CSS:

#my-element:target {
background-color: yellow;
}

This will turn the background of the element yellow whenever it is the target of the current document URL.

The :target pseudo-class can also be used in combination with other selectors to create more specific targeting. For example, to style all h2 elements when they are the target of the current document URL, you would use the following CSS:
h2:target {
color: red;
}

This will turn all h2 elements red whenever they are the target of the current document URL.

The :target pseudo-class is a powerful tool that can be used to create more user-friendly and informative web pages. By highlighting the target of the current document URL, you can help users to quickly and easily find the information that they are looking for.

Syntax

:target {
  /* ... */
}

Example

<ul> 
<li><a href="#h1">Section 1</a></li>
<li><a href="#h2">Section 2</a></li>
</ul>
<h2 id="h1">Section 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,</p>
<h2 id="h2">Section 2</h2>
<p>quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
h2:target { 
background: #fc0;
padding: 3px;
}

Browser Support

The following table will show you the current browser support for the CSS :target pseudo class.

Desktop
Edge Chrome Firefox Opera Safari
12119.51.3
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
18410.1212

Last updated by CSSPortal on: 1st October 2023