Pure CSS Highlight for Link :target

Recently I was working on a FAQ page. Typically, it had a series of Questions at the top, and each linked to an Answer below (I actually prefer questions and answers to be more Q>A, Q>A, but this was an existing page, it was the new design, and it’s how the client wanted it.

The Question looked something like this:

<a href="#faq1">Is this a really frequently asked question?</a>

And the Answer looked something like this:

<li id="faq1">Some really enlightening answer.</li>

This is pretty standard stuff, really basic HTML. But what I’ve never been crazy about is how some times, depending on the length of the page, a link could jump you down the page, but the answer wouldn’t appear at the top of the browser window, it might be “somewhere in the middle”… It can be a disorienting experience for the user…

To help alleviate this confusion, another fairly standard practice has been to write a little JavaScript that animates a background color to highlight the requested section. The animation usually jumps in, then slowly fades out. I’ve seen this a lot, and I like it a lot, and was considering adding it to the page, but there currently was no need for a JS file for this project, and I just didn’t like the idea of creating a file just for a simple highlight/fade thingy…

But there was a CSS file already…

So, keeping things simple for this example, I’m going to base this on the above HTML, and I’m only going to use (what-will-hopefully-one-day-become) the standard animation CSS; live, you would use the litany of necessary vendor prefixes, of course:

li:target {
	animation: hilite 2.5s;
}
@keyframes hilite {
	0% {background: transparent;}
	10% {background: #f8f99a;}
	100% {background: transparent;}
}

Here’s the demo page.

What you get is a jump down the page, then the desired Answer’s background color quickly fades from transparent to soft yellow, then slowly fades back to transparent. I’ve exaggerated the duration a bit to help with the effect, but obviously the color and duration are up to you and/or your designer.

It’s a really simple, yet quite elegant, highlight effect, doesn’t require any JS or JS library, and degrades to what users already get, if the CSS is not supported in their browser (check current browser support).

Note that this effect also works if you are deep-linking from another page completely, which is an even more useful occasion for the effect, when the page finishes loading and suddenly jumps before the user’s eyes, the highlight helps them know what just happened…

Happy background fading,
Atg

2 Responses to Pure CSS Highlight for Link :target

  1. aarontgrogg says:

    Sadly, for some reason, this post has been nailed again and again with spam, so I’m closing the comments. If you have something worthwhile to say, please reach out via email, Twitter, or some other form of communication.

    Cheers,
    Atg