1

When I'm nesting my checkboxes in a <div> element my code stops working. I need images to display upon checking a certain checkbox. Code works without nesting the checkboxes in a <div>.

I want my checkboxes to be nested in a <div> so that it changes the display value from none to inline-block in the <div> with the images upon selecting a certain checkbox.

I've tried everything but I think I just can't get my head around this problem.

<body>

<style>
  input[type=checkbox]:checked.ivo ~ div #fotoivo {
    display: inline-block;
 }

input[type=checkbox]:checked.ian ~ div #fotoian {
    display: inline-block;
 }

input[type=checkbox]:checked.non ~ div #fotonon {
    display: inline-block;
 }

#fotoivo {
    width: 200px;
    display: none;
}

#fotoian {
    width: 200px;
    display: none;
}

#fotonon {
    width: 200px;
    display: none;
}
</style>

<!--Checkboxes (works without the <div> wrapped around)-->
<!--<div>-->
  Ivo: <input type="checkbox" name="ivoian" class="ivo">
  Ian: <input type="checkbox" name="ivoian" class="ian">
  Non-binair: <input type="checkbox" name="ivoian" class="non">
<!--</div>-->

<!--Images that should change from display: none to inline-block.-->
  <div>
    <img id="fotoivo" src="ivo.jpg" alt="#">

    <img id="fotoian" src="ian.jpg" alt="#">

    <img id="fotonon" src="non.jpg" alt="#">
  </div>

</body>
IvoJongmans
  • 31
  • 1
  • 3

1 Answers1

0

Tilda (~) is sibling selector. When you nest the inputs, the div wrapping images isn't their sibling anymore. As CSS doesn't have parent selector, you aren't able to do it with only css. But of course, you can do it with simple JS.

You can do something like this: https://stackoverflow.com/a/7691692/11404579

Edit: also, there is little bit hacky way to do it with just CSS, but you will lose the native inputs. You can place the inputs in root element, so you can select the images with sibling selector and hide the inputs. And in some nested element place labels for those hidden inputs. This way, when you click on (nested) label, you check the input a can control the content.

crishpeen
  • 148
  • 8