CSS Target Selector
In this article, we will discuss :target pseudo-class selectors in CSS with respect to navigation. It is very useful pseudo-class selector before we proceed and understand what is syntax and how we can use it in our HTML page.
: target Selector
syntax:
selector:target{
declaration list;
}
The target pseudo-class selector selects any HTML element targeted by the selector if its status is targeted (only when the element ID or name appears as the targeted fragment identifier in the URL).
Example:
p:target{
border:2px dotted red;
}
It selects any p element which is currently a targeted fragment identifier in the page URL.
A step-by-step guide to target selector
<html>
<head>
<title>target selector</title>
</head>
<style type="text/css">
p:target{
border: 2px dotted blue;
}
</style>
<body>
<p id="top">Top Section</p>
<a href="#middle"> Middle Section</a><br>
<a href="#bottom"> Bottom Section </a>
<br><br><br><br><br>
<p id="middle">Middle Section</p>
<a href="#top"> Top Section</a><br>
<a href="#bottom"> Bottom Section </a>
<br><br><br><br><br>
<p id="bottom">Bottom Section</p>
<a href="#top"> Top Section</a><br>
<a href="#middle"> Middle Section </a>
</body>
</html>
Output:
- First, the general syntax of HTML is written and the title is set to “Target Selector”.
- In the body, we have created three sections separated by some break tags.
- Then, we added an ID attribute to all <p> tags. So, we are identifying the elements uniquely using the ID attribute.
- We created hyperlinks to move from one section to another section within the same page. So, using <a> tag to create hyperlinks.
- Finally, we use the CSS target pseudo selector and select the <p> tag and apply 2px blue border.
- See the above output, the <p> targeted fragment identifier is “bottom”. So the ID bottom is displayed 2px blue border.