This is apparently a well known CSS trick, but I just implemented it and I really like the elegance of it all. Well, despite it essentially being a hack. 😊 Besides not needing code (which means it still works when scripting is disabled), it also doesn't involve dummy anchor links, so it won't clutter your URL bar with a # when users click it.
You essentially create a checkbox which is hidden, an associated label, and then a DIV right after it. The CSS hides the checkbox, but uses the checked/not checked state of the checkbox to show or hide the DIV below it.
<style>
input.toggle {display:none}
input.toggle ~ label {cursor:pointer;}
input.toggle ~ label:hover {text-decoration:underline;}
input.toggle:checked ~ label ~ div {display:block;}
input.toggle:not(:checked) ~ label ~ div {display:none;}
</style>
<input class="toggle" type="checkbox" id="toggle1">
<label for="toggle1">This is some text the user can click</label>
<div><p>And this is some text that will show or hide based on that click</p></div>
Unfortunately I can't embed style tags in my blog, but here is a working example on JSFiddle.
Comments