CSS - Pseudo-class :target



The CSS pseudo-class :target points to a specific element, called the target element, whose id matches the fragment identifier in the URL.

Syntax

:target {
   /* css declarations */
 }

CSS :target - Linking Elements

The following example demonstrates the use of :target pseudo-class to highlight the portion of a page that has been linked to anchor tags.

Here we see that <a> tags points to #demo-target1 and #demo-target2. This points to an element called demo-target1 and demo-target2 respectively.

<html>
<head>
<style>
   #demo-target1 {
      background-color: yellow;
      padding: 10px;
      margin: 20px 20px 20px 20px;
   }
   #demo-target2 {
      background-color: lightgray;
      padding: 10px;
      margin: 20px 20px 20px 20px;
   }
   #demo-target2:target {
      background-color: red;
      color: white;
      }
   #demo-target1:target {
      background-color: red;
      color: white;
   }
</style>
</head>
<body>
<div>
<a href="#demo-target1">Click here to target the ELEMENT-1 and turn its color to red</a>
</div>
<br>
<div>
<a href="#demo-target2">Click here to target the ELEMENT-2 and turn its color to red </a>
</div>
<div id="demo-target1">
   <p>This is the target ELEMENT-1 </p>
</div>
<div id="demo-target2">
   <p> This is the target ELEMENT-2 </p>
</div>
</body>
</html>

CSS :target - No Target Exist

The following example demonstrates the how :target pseudo-class doesn't affect the links that don't have target set.

<html>
<head>
<title>:target with ID</title>
<style>
   #demo-target {
      background-color: yellow;
      padding: 10px;
   }
   #demo-target:target {
      background-color: red;
      color: white;
   }
</style>
</head>
<body>
<h1>Click on the links below to see the effect of :target with ID</h1>
<ul>
   <li><a href="#demo-target">Target Element</a></li>
   <li><a href="#other">Other Element</a></li>
</ul>
<div id="demo-target">
   <h2>This is the target element</h2>
   <p>When this element is the target of the URL fragment identifier, its background color changes to red and the text color changes to white.</p>
</div>
<div id="other">
   <h2>This is another element</h2>
   <p>This element is not affected by the :target selector.</p>
</div>
</body>
</html>
The :target doesn't work inside a web component, because the shadow root doesn't pass the target element into the shadow tree as it should.
Advertisements