2

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?

4
  • an example here codepen.io/paulobrien/pen/tpmAi Commented May 12, 2016 at 12:43
  • 1
    I don't think you can do it without js Commented May 12, 2016 at 12:43
  • 1
    why are you not use js? Commented May 12, 2016 at 12:44
  • I guess you use concepts like LESS to create it for you? But not sure if the original problem of repeating can be avoided in CSS. Commented May 12, 2016 at 12:57

1 Answer 1

1

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; }
Sign up to request clarification or add additional context in comments.

4 Comments

how this answer can solve the OP issue? He already knows this css magic, please read carefully the question.
He asked If there is a way generating less classes. So in my example you would need only one.
But OP has multiple inputs, did you read carefully the question?
He targets all inputs with this input:checked + .toggle { display: none; } line of css, so the answer is quite valid imho. However, I would probably use one separate class on all inputs to target them specifically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.