Hide Show content-list with only CSS, no javascript used

Frederic Kizar picture Frederic Kizar · Jul 18, 2013 · Viewed 207.4k times · Source

I've been searching for a good trick to make a Hide/Show content or a list with only CSS and no javascript. I've managed to make this action:

<!DOCTYPE html>
<head>

   <style>
      #cont {display: none; }
      .show:focus + .hide {display: inline; }
      .show:focus + .hide + #cont {display: block;}
   </style>

</head>
<body>

   <div>
        <a href="#show"class="show">[Show]</a>
        <a href="#hide"class="hide">/ [Hide]</a>
        <div id="cont">Content</div>
   </div>

</body>
</html>

Demo here: http://jsfiddle.net/6W7XD/ And it's working but not as it should. Here is the problem: When the content is shown, you can hide it by clicking "anywhere on the page". How to disable that? how to hide content "only" by clicking hide? Thank you in advance!

Answer

Kevin Lynch picture Kevin Lynch · Jul 18, 2013

I wouldn't use checkboxes, i'd use the code you already have

DEMO http://jsfiddle.net/6W7XD/1/

CSS

body {
  display: block;
}
.span3:focus ~ .alert {
  display: none;
}
.span2:focus ~ .alert {
  display: block;
}
.alert{display:none;}

HTML

<span class="span3">Hide Me</span>
<span class="span2">Show Me</span>
<p class="alert" >Some alarming information here</p>

This way the text is only hidden on click of the hide element