0

Im trying to add something similar to a 'dark mode' to my page. I found a good toggle switch online that when clicked activates a checkbox, how can I use the checked state of the box to change my css?

Html:

    <body>
    <div class="switch">
    <input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat" type="checkbox">
    <label for="cmn-toggle-4"></label>
    </div>
    <div id= "lbox">
    </div>
    <div id="text1">
        <p>text</p>
    </div>
    <div id="text2">
        <p>text</p>
    </div>
</body>

I'd like to change the color of lbox and the background color of body. I've tried:

input.cmn-toggle-round-flat:checked + #lbox {
color:#ffffff;
}

This only seems to work changing sections of the toggle css not outside of that. Is there anyway I can do this with pure css or will I have to use javascript somehow? Thank you.

Fastzr
  • 3
  • 2
  • Your input and the div with the ID of `lbox` aren't siblings, so `+` won't work. – j08691 Nov 16 '15 at 18:08
  • With CSS you can only select child (and sibling) elements, not parents, so it would be impossible to style the body with CSS alone based on the checked state of one of its child elements. You need to use javascript. – Mike Nov 16 '15 at 18:38
  • Possible duplicate of [Apply CSS styles to an element depending on its child elements](http://stackoverflow.com/questions/2326499/apply-css-styles-to-an-element-depending-on-its-child-elements) – Mike Nov 16 '15 at 18:40

1 Answers1

0

Css is for styling.. if you have some logic you have to call Mr Javascript (jQuery) ;)

Its Easy. i just made a little snippet. hope it helps

$(document).ready(function(){
  
  $('#cmn-toggle-4').click(function(){
    if($(this).is(":checked")){
      $('.wrap').css('background','black');
      $('p').css('color','white');
    }else {
      $('.wrap').css('background','white');
      $('p').css('color','black');
    }
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
    <div class="switch">
    <input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat" type="checkbox">
    <label for="cmn-toggle-4"></label>
    </div>
    <div id= "lbox">
    </div>
    <div id="text1">
        <p>text</p>
    </div>
    <div id="text2">
        <p>text</p>
    </div>
</div>
shakee93
  • 3,769
  • 2
  • 23
  • 29