Reputation: 474
I have a project where I show and hide elements using checkboxes in conjunction mit CSS only. The following pattern, see also https://jsfiddle.net/37bqmbuo/, works for me.
HTML:
<input class="switch-1" type="checkbox">
<input class="switch-2" type="checkbox">
<input class="switch-3" type="checkbox">
<div class="hidden-1 hidden-2">Info 1</div>
<div class="hidden-2 hidden-3">Info 2</div>
<div class="hidden-1 hidden-3">Info 3</div>
<div class="hidden-1">Info 4</div>
<div class="hidden-3">Info 5</div>
CSS:
.switch-1:checked ~ .hidden-1
{
display: none;
}
.switch-2:checked ~ .hidden-2
{
display: none;
}
.switch-3:checked ~ .hidden-3
{
display: none;
}
But the more options I have, the more classes I need to create. Is there a smarter way to implement this with CSS only?
Upvotes: 2
Views: 5465
Reputation: 153
Actually, there is.
Put the element you want to target after the input like so:
<input type="checkbox" value="My Checkbox" />
<div class="toggle">Toggle me</div>
and do some CSS magic:
input:checked + .toggle { display: none; }
Upvotes: 1