CSS ::target-text
The ::target-text pseudo-element in CSS allows you to style text of an active anchor target. It is particularly useful for scenarios where you want to highlight the text of a linked element when it is targeted via an anchor link. When a piece of content is targeted, all the elements corresponding to the target can be styled differently. This is particularly beneficial for creating interactive and visually engaging web interfaces.
In this tutorial, we will create a simple example using fictional data to demonstrate how the ::target-text pseudo-element works.
<style>
/* Basic styling for the target text */
#section1:target-text {
color: blue;
font-weight: bold;
}
/* General styles */
section {
margin: 20px;
padding: 10px;
border: 1px solid #ccc;
}
</style>
<h2>Anchor Links</h2>
<p>Click the links below to see the target text change:</p>
<a href="#section1">Go to Section 1</a>
<a href="#section2">Go to Section 2</a>
<h3 id="section1">Section 1</h3>
<p>This text will change when you click the link above.</p>
<h3 id="section2">Section 2</h3>
<p>This text will not change when you click the first link.</p>
In the example above:
- The
tag with the IDsection1becomes the target when you click the "Go to Section 1" link. - The text within the
section1will be styled according to the::target-textrule you define in the CSS. - While the text in Section 2 remains unaffected by the link to Section 1.
You can experiment with different styles applied via ::target-text to enhance the user experience and create a more interactive site.