skip to content

CSS :target Trick


The CSS :target trick works by matching the hash(#) in the URL, to the ID of an element.

Consider the following URL https://triss.dev/blog/2019/10/02/css-target-trick/#targetTrick

If the page contains an element with the ID of #targetTrick, the following selector will match and apply:

#targetTrick:target {
 background: PapayaWhip;
}

Click this link: #targetTrick and notice how the url now includes #targetTrick which matches the ID on the body element.

This means that the selector above is valid and the background-color is applied.

Examples

You can do lots of awesome things with this trick. Here are a few examples:

Sidebar navigation

See the Pen Tabs (checkbox-hack) by Tristan White (@triss90) on CodePen.

Fluid responsive navigation

See the Pen Tabs (checkbox-hack) by Tristan White (@triss90) on CodePen.