0

I have a check-box, and want to change the background-color of body when that is checked, with pseudo-class ":checked". Is there any way to do this? I'll be thankful for any answer;

      <label>
        <input id = "night" type = "checkbox">
        <span>Night</span>
      </label>
#night:checked {
    background-color: #242729;
}
  • When you say body, do you mean the actual body tag of the HTML document or do you mean that span tag within the label? If you mean the body tag, you're going to need JS. If you just mean the span tag, then you could do input[type=checkbox]:checked ~ span {background-color: #242729;} – Sivak Nov 15 '20 at 07:37
  • i would suggest is to use a script. jquery, and add a function id to the body and get the value of the checkbox that would change is property. https://stackoverflow.com/questions/2834350/get-checkbox-value-in-jquery. – keith montajes Nov 15 '20 at 07:39

3 Answers3

1

using jquery you can do it like this

    $('#night').change(function(){
      let color = $(this).is(':checked') ? 'black' : 'white';
      $('body').css('background-color', color);
    });

I don't know how to do in pure css, sorry

Marc Salvetti
  • 352
  • 1
  • 10
0

You can achieve this with pure css like so,

<input type="checkbox" id="cb_1" value="cb_val" name="cb_name">
<label for="cb_1">
     my checkbox text
</label>

With this css,

label { background-color:#333; color:#FFF; }

input[type="checkbox"]:checked + label {
    background: brown;
}

Keep in mind

The label has to be after the checkbox so you will need to style it around more to keep the same look you had.

Here is an option of styling it more to have the same appearance as you wanted, New fiddle. THIS DOES NOT involve positioning anything absolute, just some trickery.

Kashaf Ahmed
  • 67
  • 2
  • 10
0

If you are trying to do it with the body tag then it is not possible with Pure CSS. But you can if you will create a different "body" and "+" selector. You can check this link for an example

<input id="night" type="checkbox" hidden>
<div class="body">
  <label for="night">Click to Switch Mode</label>
</div>

Good luck and cheers!

Yor
  • 182
  • 6