0

I am trying to have a checkbox change the content of a div but if the content isn't together (in the same div), then it will not work.

HTML:

<div>
   <input type="checkbox" id="check">
   <label for="check">Hello</label>
</div>

<div class="check"></div>

CSS:

.check:before {
   display: block;
   width: 100px;
   height: 100px;
   background: red;
   content:'';
}

input:checked ~ .check:before {
   content:'Content';
}

JSFiddle: https://jsfiddle.net/pgkwn4j6/

Tim
  • 4,560
  • 2
  • 40
  • 64

2 Answers2

0

In your example one thats working is using "input:checked ~ .check:before" which selects "check" class div that is preceeding right after the input that is checked(sibling elements).

When you the put the label and input in a different div tag you need to select parent`s sibling which is not possible through css.

You can do it through Jquery.

CSS: how to select parent's sibling

above question showcases very similar problem you are having.

Community
  • 1
  • 1
Saa_keetin
  • 647
  • 6
  • 10
0

It does not work because it is not in the same div, in css you can not manipulate any element outside the parent element. To be able to manipulate an element outside you have to use jquery. Here your JSfiddle correct link:

JSFiddle Correct

$(document).ready(function(e) {
  $('input#check').click(function(){
    $('.check').toggleClass('show-content');
  });
});
Sieen
  • 68
  • 2
  • 11