← All elements

Theme Switch With :has()

by @admin · 10 views

<div class="app"><label class="t"><input type="checkbox"><span>☀</span><span>☾</span></label><h3>Hello there</h3><p>This card changes theme with no script.</p></div>

About this layout

A light and dark theme toggle where :has() lets the wrapper react to a checkbox, with the palette held in custom properties.

How it works

The card holds a checkbox, and the parent uses :has(input:checked) to react to it. Instead of restyling every child, the rule only changes four custom properties for background, text, subtitle and chip colours. Everything else reads those variables, so the whole card switches theme in one step with a smooth colour transition.

Ways to customise it

  • Add more variables, such as a border or shadow colour, to the :has() rule.
  • Move the variables to :root to theme a whole page the same way.
  • Change the knob colour to match your accent.

Good to know

The :has() selector works in current Chrome, Safari, Edge and Firefox, but not in older browsers, where the card simply stays light. For real sites also respect prefers-color-scheme as the starting value.

Open an example, copy the HTML and the CSS, and paste them into your page. There is nothing to install and no JavaScript to load.

More in Layout

View all →