Mike's web site

A handmade site with some stuff

Using CSS to make spoiler text for PC and mobile

Tech Tip

I searched around and could not find any single webpage that showed how to use CSS to make "spoiler text" that would work for non-touch screens (like a PC) and touch screens (like a phone). So here it is!

We will use a button element. It will look like a black box until the user hovers the cursor over it (PC) or taps on it (mobile). First start with a class to separate this type of button from any other button:

.b-spoil {
  color: black;
  background-color: black;
  border: 0 white;
}

The border color should be the color of your background. You might need to add in font-style to match your font.

Next we show the text on hover (for PCs):

.b-spoil:hover {
  background-color: white;
}

At the risk of being obvious, the background-color should be the color of your background.

And now the pseudo-class for phones:

.b-spoil:focus {
  background-color: white;
}

The focus pseudo-class means that when the button has focus (tapped, or even moved to via keyboard navigation), the background-color changes to white. This happens on phones when you tap on the black box. Tapping somewhere else will hide the text again.

Here's how you implement this in html:

<p>Who killed Mr. Smith? <button class="b-spoil">
     The butler did it!</button><p>

Which will show up like this:

Who killed Mr. Smith?

Note this will work on PCs by hovering or tapping. I hope this has been helpful!

At this time I will not maintain a comment forum on this site. If you'd like to comment, please do so on my Twitter feed @MichaelOlgren.