-3

This question is purely hypothetical; I don't intend to use the methods discussed here. The intention is to learn more about CSS selectors.

Consider an HTML page containing a checkbox. If the checkbox is selected, the background of the body element is red. Otherwise it is blue.

Is this possible to achieve using currently usable selectors in CSS?

Here are the constraints:

  • No javascript anywhere
  • No divs overlaying the entire page. It must be the body element's background property.
  • No future CSS selectors like :has. Ideally the method should be demonstrable in a Codepen.
kubuzetto
  • 874
  • 6
  • 26
  • I am flagging this because it will most likely lead to opinion-based answers. – 10 Rep Jul 14 '20 at 18:48
  • 1
    no, there is no parent selector and you can not use future stuff. – epascarello Jul 14 '20 at 18:48
  • If you change the structure of the page and do not use body, there are ways to sort of do it with a wrapper class. – epascarello Jul 14 '20 at 18:50
  • I know there is no parent selector. It wouldn't be the only way to pull it off though. If you had a way to select the root (not the immediate parent node, but to the document for example), or set a CSS variable there, it would achieve the task. A proper 'no' answer should eliminate these possibilities. – kubuzetto Jul 14 '20 at 18:54
  • So the answer is NO because of *"It must be the body element's background property."*. Have a nice day. – epascarello Jul 14 '20 at 18:57

1 Answers1

0

Here's one way. It satisfies all your conditions, but it does use a pseudo-element so it sort of cheats on the "It must be the body element's background property" requirement since the body's background color is set, but the red color comes from the pseudo element:

input:checked::before {
  content: '';
  position: absolute;
  background: red;
  z-index: -1;
  top:0;
  right:0;
  bottom:0;
  left:0;
}

body {
  margin: 0;
  background: blue;
}
<input type="checkbox">
j08691
  • 190,436
  • 28
  • 232
  • 252