Skip to main content

Explaining the Basics of a Show/Hide Implementation of the CSS :target

I found the code on StackOverflow for a simple CSS based hide/show scenario, it is an incredibly short piece of code, but for the uninitiated it is difficult to understand at first what is actually going on.

So what I did first is to break down the CSS into what happens at page load time and what happens at the point at which a target is linked to:
/* happens on load */
.answer,
#show
{
    display: none; 
}

/* happens when show is clicked */
#hide:target {
    display: none; 
}

#hide:target + #show,
#hide:target ~ .answer {
    display: inline; 
}
To explain:
  1. At load time any element where the class is answer or the id is show is set not to display. 
When a target with an id of hide is "targeted", i.e. from a link with <a href="#hide">[Text]</a>, then:
  1. the content with the hide id will not display.
  2. any element with the show id that immediately follows the target will display, as will any element with the class of answer which follows that hide target at any point.
There is no code whatsoever here that handles the hiding of content based on a link being clicked.

Let's now look at the HTML
<a href="#hide" id="hide">Show</a>
<a href="#" id="show">Hide</a>
<div class="answer">
Answer</div>
Here we see that the hiding happens by a simple reload of the page, which occurs through an empty target being clicked. This reinstates what happened when the page first loaded and returns us to a state where elements with the class answer are hidden along with those with the id show. (Note: as with all HTML the id should be a unique value only appearing once on a page, whereas the class name can be repeated.)

Comments