Light / Dark Mode Made Simple with CSS light-dark()

Now, light and dark mode toggling is simple with just CSS—no need for complex processes or JavaScript. A single HTML element and a few lines of CSS handle theme switching effortlessly.

Here’s a fully prepared, end-to-end light/dark mode toggle example just for you.

:root {
  // Define color scheme with dark mode as default
  color-scheme: dark;

  // Switch to light mode when the toggle input is checked
  &:has(input[name="toggleSwitch"]:checked) {
    color-scheme: light;
  }

  // Define light and dark color variables
  --color-body: light-dark(#fff, #000);
  --color-icon-bg: light-dark(#f6f8fa, #21262d);
  --color-icon-border: light-dark(#e2e7ef, #30363d);
  --color-icon-icon: light-dark(#2e2e48, #fff);
}

body {
  background-color: var(--color-body);
}

.toggleContainer {
  input[name="toggleSwitch"] {
    display: none; // Hide the input switch

    // Apply style changes when the input is checked
    &:checked + label svg {
      transform: rotate(180deg); // Rotate the icon on toggle
    }
  }

  label {
    cursor: pointer;

    svg {
      transition: all 0.3s ease; // Smooth rotation
      width: 70px;
      height: 70px;

      // Use variable colors for the icon parts
      .toggleIcon__bg {
        fill: var(--color-icon-bg);
      }
      .toggleIcon__border {
        stroke: var(--color-icon-border);
      }
      .toggleIcon__symbol {
        fill: var(--color-icon-icon);
      }
    }
  }
}

Browser compatibility

https://caniuse.com/mdn-css_types_color_light-dark

Buy Me A Coffee

Explore More Posts