user3283304
user3283304

Reputation: 149

Changing CSS based on input checked

Apologies in advance because I know this is a silly question. I am using the following CSS code to change the background color of a label when it's associated checkbox is checked:

#project input[id="button1"]:checked + label {background-color:red;}

I want to ALSO change the background color of the entire page when id="button1" is checked. Is that possible? I tried adding to the line and a new line with no success:

input[id="button1"]:checked {background-color:blue;}

Shouldn't that affect the background outside the DIV? I can't figure it out. The finished product should have both the label background color and the page background color connected to the state of the checkbox.

Upvotes: 0

Views: 1074

Answers (2)

knitevision
knitevision

Reputation: 3143

Via pure CSS events you can only change styles of the elements that are children of the element that toggled the event. Your body is never a children of the checkbox input (unless you are high). So the only option is some JavaScript/jQuery.

Basic simple example

var button = document.getElementById('button1');

button.addEventListener('click', function() {
    document.querySelector('body').classList.toggle('blue');
});

Upvotes: 1

c-smile
c-smile

Reputation: 27460

input[id="button1"]:checked {background-color:blue;}

"Shouldn't that affect the background outside the DIV?" - no, it will affect only that input element.

In general you cannot do that by only CSS means as you will need hypothetical :contains selector:

body:contains(input[id="button1"]:checked) {background-color:blue;}

Unfortunately that :contains has very high computational complexity to be implemented in CSS in general.

Upvotes: 1

Related Questions