Pseudo- classes in CSS: Highlighting Page Fragments with :target

A fragment identifier is the part of a URL starting with a # character-such as #top or #footnote1 . You may have used them to create in-page navigation links-sometimes called  “jump links”. With the :target pseudo-class, we can highlight the portion of the document that corresponds to that fragment.

Say, for example, you have a series of comments in a discussion board thread:

<section id=”comments”>
<h2>Comments</h2>
<article class=”comment” id=”comment-1146937891″>…</article>
<article class=”comment” id=”comment-1146937892″>…</article>
<article class=”comment” id=”comment-1146937893″>…</article>
</section>

With some CSS and other fancy bits, it might look a little like what’s pictured below.

Each comment in the code above has a fragment identifier, which means we can link directly to it with an anchor link such as <a href=”#comment-ii4693789i”> or <a href=”http://exampLe.com/post/#comment-1146937891″> . Then all we need to do is specify a style for this comment using the :target pseudo-class:

.comment:target {

background: #ffeb3b;

border-color: #ffc107

}

When someone clicks a link to an <articLe> element with a class of comment, the browser will take them to that comment and give it a yellow background, as shown below.

You can use any combination of CSS with :target , but be cautious about using properties that can show or hide content. Adjusting the z-index property, for example, can hide content on the page, but still expose it to assistive technology. That may not be what you want.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *