The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1

40 Chapter 4


:target


On the Web, sites don’t just link between pages but also provide internal
links to specific elements. A URI can contain a reference to a unique ID or
a named anchor. For example, if you had this markup in a page:

<h4 id="my_id">Lorem ipsum</h4>

you could refer to it with this link:

<a href="page.html#my_id">Lorem</a>

The :target pseudo-class allows you to apply styles to the element when
the referring URI has been followed. In this example, if you want to apply
styles to the h4 element when the URI is followed, you use:

#my_id:target {...}

A popular practice is to highlight the subject of an internal link visually
to provide a clear cue to the user. Consider, for example, the standard pat-
tern for blog comments, which are somewhat like this simplified markup:

<div class="comment" id="comment-01">
<p>Thanks for this scintillating example!</p>
<p class="author">N.E. Boddy, April 13</p>
</div>

And another fairly common pattern is to include links to individual
comments:

<p><a href="#comment-02">Latest comment</a></p>

Using the :target pseudo-class, you can easily highlight the comment
that the user wants to read:

.comment:target { background-color: #DDD; }

Figure 4-7 shows a list of comments in two states: on the left, as they
appear before the referring link has been clicked, and on the right, as
they appear after the link has been clicked—with the element that the
link refers to showing a different background color thanks to the :target
selector.
Free download pdf