Charles Harries

| Stream

:target navigation

If you're in need of an extremely basic client-side router that uses no JS at all, have I got news for you!

The :target CSS selector doesn't get the love it deserves. I'm at pains to find a spot anywhere on the Internet where I've seen it used to much effect; it's usually elbowed out by :active for hash navigation within a page.

What it does, in basic terms, is give you a handle for styling elements when their id attribute matches the URL's current hash. So e.g. given some markup like

<style>
#about {
	color: blue;
}

#about:target {
	color: red;
}
</style>

<p id="about">About me</p>

If the current URL is example.com/#about, the text will show up in red; otherwise, it'll show in blue.

The above example isn't very useful, even if it is (hopefully) illustrative. But :target allows us to do other fun stuff, like create a very simple client-side no-JS router based entirely on the page hash:

Web Code