Open In App

CSS :target Selector

Improve
Improve
Like Article
Like
Save
Share
Report

The target selector is used to represent a unique element (the target element) with an id matching the URL’s fragment. It can be used to style the current active target element. URLs with a # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. 

Syntax:

:target {
    // CSS Property
} 

Example 1: In this example, The :target selector applies CSS styles to the target element specified in the URL fragment, allowing customization based on the target element.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>CSS | :target Selector</title>
    <style>
        /* CSS property of target selector */
        :target {
            border: 2px solid #D4D4D4;
            background-color: green;
            color: white;
            padding: 10px;
            font-size: 20px;
        }
    </style>
</head>
 
<body style="text-align:center">
    <h2>
        :target selector
    </h2>
 
    <p>
        <a href="#geek">
            Jump to Algorithms
        </a>
    </p>
 
    <p id="geek">
        <b>Algorithms</b>
    </p>
 
</body>
 
</html>


Output: 

algo.gif

Example 2: In this example, The :target selector is used to styling the targeted element based on the URL fragment, showing content dynamically.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>:target Selector</title>
    <style>
        .tab div {
            display: none;
        }
 
        .tab div:target {
            display: block;
            color: white;
            background: green;
            padding: 5px;
            margin: 20px 5px;
        }
    </style>
</head>
 
<body style="text-align:center">
    <h2>
        :target selector
    </h2>
    <div class="tab">
        <a href="#geek">Geeks Classes</a>
        <div id="geek">
            <h3>Welcome to Geeks Classes.</h3>
 
            <p>Hello World!</p>
 
        </div>
    </div>
</body>
 
</html>


Output: 

algo-2.gif

Supported Browsers: The browser supported by :target Selector are listed below:

  • Apple Safari 1.3
  • Google Chrome 1.0
  • Edge 12.0
  • Firefox 1.0
  • Opera 9.5


Last Updated : 05 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads