2

I have the following code:

<!doctype html>
<html>
<head>
</head>
<body>
  <div id="color-wrapper">
    Hello world
  </div>

  <input id="dark-mode" type="checkbox">
  <label for="dark-mode">Dark mode</label>
</body>
<style>
:root {
  --bg: pink;
}

#dark-mode:checked ~ #color-wrapper {
  --bg: orange;
}

#color-wrapper {
  background: var(--bg);
}
</style>
</html>

It has to change background color of the "Hello world" text then I check the checkbox, but it does not, the color is always pink. What is the problem?

1 Answers1

3

The tilde selector ~ selects siblings after the element, so change order of elements in your html to fix:

:root {
  --bg: pink;
}

#dark-mode:checked ~ #color-wrapper {
  --bg: orange;
}

#color-wrapper {
  background: var(--bg);
}
  <input id="dark-mode" type="checkbox">
  <label for="dark-mode">Dark mode</label>
    <div id="color-wrapper">
    Hello world
  </div>
protob
  • 3,317
  • 1
  • 8
  • 19