Skip to main contentSkip to docs navigation

Chassis

Color modes

View on GitHub

Explore Chassis CSS color modes — the default light mode, dark mode, and how to create custom themes using the data-cx-theme attribute.

Dark mode

Chassis CSS has two color modes, light and dark. Every color token carries both values, and the mode decides which one is used:

  • With no attribute, the page follows the system preference of the visitor.
  • data-cx-theme="light" or data-cx-theme="dark" sets the mode of an element and of everything inside it: on the <html> element for the whole page, or on a single component. The nearest attribute wins.

Tailwind CSS projects using the Tailwind entry point get dark: and light: variants that follow the same rule, on every utility. In the native build, the dark: classes of the utility API follow the system preference only.

Example

For example, to change the color mode of a dropdown menu, add data-cx-theme="light" or data-cx-theme="dark" to the parent .dropdown. Now, no matter the global color mode, these dropdowns will display with the specified theme value.

HTML
<div class="dropdown" data-cx-theme="light">
  <button class="button secondary caret" type="button" id="dropdownMenuButtonLight" data-cx-toggle="menu" aria-expanded="false">
    Default dropdown
  </button>
  <ul class="menu" role="menu" aria-labelledby="dropdownMenuButtonLight">
    <li><a class="menu-item active" href="#">Action</a></li>
    <li><a class="menu-item" href="#">Action</a></li>
    <li><a class="menu-item" href="#">Another action</a></li>
    <li><a class="menu-item" href="#">Something else here</a></li>
    <li><hr class="menu-divider"></li>
    <li><a class="menu-item" href="#">Separated link</a></li>
  </ul>
</div>

<div class="dropdown" data-cx-theme="dark">
  <button class="button secondary caret" type="button" id="dropdownMenuButtonDark" data-cx-toggle="menu" aria-expanded="false">
    Dark dropdown
  </button>
  <ul class="menu" role="menu" aria-labelledby="dropdownMenuButtonDark">
    <li><a class="menu-item active" href="#">Action</a></li>
    <li><a class="menu-item" href="#">Action</a></li>
    <li><a class="menu-item" href="#">Another action</a></li>
    <li><a class="menu-item" href="#">Something else here</a></li>
    <li><hr class="menu-divider"></li>
    <li><a class="menu-item" href="#">Separated link</a></li>
  </ul>
</div>

How it works

  • Every color token is written once on :root, with its light and its dark value in the CSS light-dark() function. The color-scheme property picks the value: :root declares light dark, which follows the system preference, and the attribute sets one of the two.

    CSS
    :root {
      color-scheme: light dark;
      --cx-default-bg-main: light-dark(oklab(100% 0 0), oklch(18.49% 0.004 229.03deg));
    }
    
    [data-cx-theme="dark"] {
      color-scheme: dark;
    }
    
    [data-cx-theme="light"] {
      color-scheme: light;
    }
  • color-scheme is inherited, so the attribute works on any element. On the <html> element it applies to everything; on a component it is scoped to that component, whatever the mode of the page.

  • The icons of form controls, such as the caret of a select and the mark of a checkbox, are SVG images with their color written in, which light-dark() cannot reach. Chassis declares them once per mode: the light ones on :root, the dark ones for data-cx-theme="dark" and for a dark system preference.

  • The dark values are Sass variables of their own, in scss/tokens/_colors-dark.scss, next to the light ones in scss/tokens/_colors.scss. Both read the design tokens.

Usage

Enable dark mode

Dark mode needs no setup: a page with no attribute is dark for a visitor whose system prefers dark. To show one mode whatever the system prefers, add data-cx-theme="dark" or data-cx-theme="light" to the <html> element. It applies to all components and elements, other than those with a data-cx-theme attribute of their own. Building on the Quick Start template:

HTML
<!doctype html>
<html lang="en" data-cx-theme="dark">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Chassis CSS demo</title>
    <link href="https://cdn.jsdelivr.net/npm/@chassis-ui/css@0.16.0/dist/css/chassis.min.css" rel="stylesheet" integrity="sha384-SFRH401sQ3IrDUd2uF6pe7Amqy0xTb0Z/1Sf9+uGIH0CzEYCsNVuKL3U2ocGAZq2" crossorigin="anonymous">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <script src="https://cdn.jsdelivr.net/npm/@chassis-ui/css@0.16.0/dist/js/chassis.bundle.min.js" integrity="sha384-iwdJNOP9WQ1eqfuNGgRC9WMeGlukmXIbl8VlndmT0MKeuYv/ZgtgTQkm/BrnUvxt" crossorigin="anonymous"></script>
  </body>
</html>

Chassis CSS does not yet ship with a built-in color mode picker, but you can use the one from the Chassis documentation. Learn more in the JavaScript section.

Building with Sass

Disable dark mode entirely by setting $enable-dark-mode to false. Every color token then has its light value alone, the dark icons of form controls are left out, and data-cx-theme="dark" changes nothing.

SCSS
@use "@chassis-ui/css/scss/config" with (
  $enable-dark-mode: false
);
@use "@chassis-ui/css/scss/chassis";

For a color of your own, write light-dark() or use a token of the framework, and it follows the mode like every other color. For anything else that differs between the modes, such as an image, use the color-mode() mixin inside the rule of the element. Its styles follow the same rule as the colors: the nearest data-cx-theme, and the system preference where no attribute is set.

SCSS
@use "@chassis-ui/css/scss/mixins" as *;

.logo {
  background-image: url("logo.svg");

  @include color-mode(dark) {
    background-image: url("logo-dark.svg");
  }
}

Outputs to:

CSS
.logo {
  background-image: url("logo.svg");
}
.logo[data-cx-theme=dark],
.logo:where([data-cx-theme=dark] *):not(:where([data-cx-theme=dark] [data-cx-theme=light] *)) {
  background-image: url("logo-dark.svg");
}

@media (prefers-color-scheme: dark) {
  .logo:not(:where([data-cx-theme=light], [data-cx-theme=light] *)) {
    background-image: url("logo-dark.svg");
  }
}

The selectors look one theme up: an element in a dark theme, inside a light theme, inside another dark theme does not get the dark styles.

Outside a rule, the mixin cannot name the element, so it writes its content under the theme and under the root of a page that follows the system preference. A light theme inside such a dark page then needs the light styles declared as well, with color-mode(light).

SCSS
@use "@chassis-ui/css/scss/mixins" as *;

@include color-mode(dark) {
  .logo {
    background-image: url("logo-dark.svg");
  }
}

Outputs to:

CSS
[data-cx-theme=dark] .logo {
  background-image: url("logo-dark.svg");
}

@media (prefers-color-scheme: dark) {
  :root:where(:not([data-cx-theme=light])) .logo {
    background-image: url("logo-dark.svg");
  }
}

The $color-mode-type variable sets what the mixin follows. It changes the mixin only: the colors of the framework always follow both the attribute and the system preference.

ValueThe styles of color-mode() follow
auto (default)The data-cx-theme attribute and the system preference, as the colors do.
dataThe data-cx-theme attribute only.
media-queryThe prefers-color-scheme media query only.

With data, call the mixin outside a rule:

SCSS
@use "@chassis-ui/css/scss/config" with (
  $color-mode-type: data
);
@use "@chassis-ui/css/scss/mixins" as *;

@include color-mode(dark) {
  .logo {
    background-image: url("logo-dark.svg");
  }
}

Outputs to:

CSS
[data-cx-theme=dark] .logo {
  background-image: url("logo-dark.svg");
}

And when setting to media-query:

SCSS
@use "@chassis-ui/css/scss/config" with (
  $color-mode-type: media-query
);
@use "@chassis-ui/css/scss/mixins" as *;

@include color-mode(dark) {
  .logo {
    background-image: url("logo-dark.svg");
  }
}

Outputs to:

CSS
@media (prefers-color-scheme: dark) {
  .logo {
    background-image: url("logo-dark.svg");
  }
}

Custom color modes

While the primary use case for color modes is light and dark mode, custom color modes are also possible. Create your own data-cx-theme selector with a custom value as the name of your color mode, then declare the CSS variables that the theme changes.

For example, you can create a theme on the primary color with the selector data-cx-theme="primary". In your custom Sass or CSS file, add the new selector with up to four kinds of declarations:

  • color-scheme — every color token has a light and a dark value. Set color-scheme to light or dark to choose the value of every token that the theme leaves alone.
  • Tokens — the colors of a context, such as --cx-default-bg-main of the body context or --cx-primary-fg-main. Forms, menus, tables and every component with a context class read them.
  • Body colors — --cx-bg-main, --cx-fg-main and the other body colors are resolved from the tokens of the body context on :root. On any other element, declare the ones whose token the theme changed again, so that they follow inside the theme. A theme on the <html> element needs no such declaration.
  • Component variables — such as --cx-menu-bg-color, where a component needs a value of its own.
[data-cx-theme="primary"] {
  // The colors that the theme leaves alone take their dark value
  color-scheme: dark;

  // The tokens of the body context that the theme changes
  --cx-default-bg-main: var(--cx-primary-70);
  --cx-default-bg-even: var(--cx-primary-60);
  --cx-default-bg-evident: var(--cx-primary-50);
  --cx-default-bg-highlight: var(--cx-primary-60);
  --cx-default-fg-highlight: var(--cx-white);
  --cx-default-border-main: var(--cx-primary-40);

  // The body colors that `:root` resolved from those tokens, declared again
  --cx-bg-main: var(--cx-default-bg-main);
  --cx-bg-even: var(--cx-default-bg-even);
  --cx-bg-evident: var(--cx-default-bg-evident);
  --cx-bg-highlight: var(--cx-default-bg-highlight);
  --cx-fg-highlight: var(--cx-default-fg-highlight);
  --cx-border-main: var(--cx-default-border-main);

  // Component variables, where a component needs a value of its own
  .menu {
    --cx-menu-bg-color: var(--cx-primary-80);
  }

  .button.secondary {
    --cx-button-idle-bg-color: transparent;
    --cx-button-idle-fg-color: var(--cx-white);
    --cx-button-idle-border-color: var(--cx-white);
    --cx-button-hover-bg-color: var(--cx-primary-60);
    --cx-button-hover-fg-color: var(--cx-white);
    --cx-button-hover-border-color: var(--cx-white);
    --cx-button-press-bg-color: var(--cx-primary-50);
    --cx-button-press-fg-color: var(--cx-white);
    --cx-button-press-border-color: var(--cx-white);
  }
}
Example primary theme

Some paragraph text to show how the primary theme might look with written copy.


The theme only declares variables. Add .fg-main and .bg-main to the element with the attribute to give it the text and background color of the theme.

HTML
<div class="fg-main bg-main" data-cx-theme="primary">
  ...
</div>

JavaScript

To allow visitors to toggle color modes, create a toggle element that controls the data-cx-theme attribute on the root <html> element. The Chassis docs ship a toggler that initially defers to the system color mode but provides an option to override it and pick a specific mode.

The JavaScript below powers it. Inspect the Chassis docs navbar to see how it's implemented using Chassis components. Include it at the top of the page to reduce screen flickering on reload. A page that only follows the system preference needs no script.

JavaScript
/*!
 * Color mode toggler for Chassis's docs (https://chassis-ui.com/)
 * Copyright 2011-2025 The Chassis Authors
 * Licensed under the Creative Commons Attribution 3.0 Unported License.
 */

;(() => {
  'use strict'

  const getStoredTheme = () => localStorage.getItem('theme') || 'auto'
  const setStoredTheme = (theme) => localStorage.setItem('theme', theme)

  const getPreferredTheme = () => {
    const storedTheme = getStoredTheme()
    if (storedTheme) {
      return storedTheme
    }

    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  }

  const setTheme = (theme) => {
    if (theme === 'auto') {
      document.documentElement.setAttribute(
        'data-cx-theme',
        window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
      )
    } else {
      document.documentElement.setAttribute('data-cx-theme', theme)
    }
  }

  setTheme(getPreferredTheme())

  // The page can hold more than one toggler (the navbar and the navigation dialog of small
  // screens). Each is a `[data-cxd-theme-toggler]` button with its own `.theme-icon-active`
  // and `[data-cxd-theme-text]`; the menu items of every toggler are kept in step.
  const showActiveTheme = (theme, focusFrom = null) => {
    const togglers = document.querySelectorAll('[data-cxd-theme-toggler]')

    if (togglers.length === 0) {
      return
    }

    const buttonToActive = document.querySelector(`[data-cx-theme-value="${theme}"]`)

    if (!buttonToActive) {
      return
    }

    const svgOfActiveButton = buttonToActive.querySelector('svg use').getAttribute('href')

    document.querySelectorAll('[data-cx-theme-value]').forEach((element) => {
      const selected = element.dataset.cxThemeValue === theme
      element.classList.toggle('selected', selected)
      element.setAttribute('aria-pressed', String(selected))
    })

    togglers.forEach((toggler) => {
      const text = toggler.querySelector('[data-cxd-theme-text]')
      const icon = toggler.querySelector('.theme-icon-active use')
      icon?.setAttribute('href', svgOfActiveButton)
      if (text) {
        toggler.setAttribute('aria-label', `${text.textContent.trim()} (${theme})`)
      }
    })

    if (focusFrom) {
      const menu = focusFrom.closest('.menu')
      const toggler = menu?.previousElementSibling
      ;(toggler?.matches('[data-cxd-theme-toggler]') ? toggler : togglers[0]).focus()
    }
  }

  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    const storedTheme = getStoredTheme()
    if (storedTheme !== 'light' && storedTheme !== 'dark') {
      setTheme(getPreferredTheme())
    }
  })

  window.addEventListener('DOMContentLoaded', () => {
    showActiveTheme(getPreferredTheme())

    document.querySelectorAll('[data-cx-theme-value]').forEach((toggle) => {
      toggle.addEventListener('click', () => {
        const theme = toggle.getAttribute('data-cx-theme-value')
        setStoredTheme(theme)
        setTheme(theme)
        showActiveTheme(theme, toggle)
      })
    })
  })
})()

CSS

Variables

:root declares every color token once, with its light and its dark value in light-dark(); no variable is repeated for dark mode. Only the icons of form controls are declared once per mode. Custom color modes lists what a theme of your own declares.

Sass variables

The dark values come from the Sass variables of scss/tokens/_colors-dark.scss, which the maps of scss/maps/_colors-dark.scss collect. $enable-dark-mode and $color-mode-type are in scss/config/_settings.scss.

Sass mixins

The color-mode() mixin applies your own styles to the light mode, the dark mode or a theme of your own. See the Sass usage section for more details.

/// Apply styles for a specific color mode (`light`, `dark` or a theme of a project).
///
/// `$color-mode-type` sets what the styles follow:
/// - `auto` (default): the system preference and the `data-cx-theme` attribute,
///   as the colors of the framework do. Inside a rule, the styles go to the
///   element of that rule when its nearest theme is `$mode`, or when it has no
///   theme and the system prefers `$mode`. Outside a rule, the content is
///   written under `[data-cx-theme="{mode}"]`, and under `:root` for the system
///   preference when the root has no theme of the other mode.
/// - `data`: the `[data-cx-theme="{mode}"]` attribute only.
/// - `media-query`: the `(prefers-color-scheme: {mode})` media query only.
///
/// A mode other than `light` and `dark` has no system preference: it follows
/// the attribute.
///
/// @param {String} $mode [light] - Color mode: `light`, `dark` or the name of a theme
/// @param {Boolean} $root [false] - With `media-query`, puts the content in `:root` inside the media query
/// @content Styles to apply for this color mode
/// @example
///   .element {
///     @include color-mode(dark) { background: black; }
///   }
///   // => .element[data-cx-theme="dark"],
///   //    .element:where([data-cx-theme="dark"] *):not(:where([data-cx-theme="dark"] [data-cx-theme="light"] *)) { background: black; }
///   //    @media (prefers-color-scheme: dark) {
///   //      .element:not(:where([data-cx-theme="light"], [data-cx-theme="light"] *)) { background: black; }
///   //    }
@mixin color-mode($mode: light, $root: false) {
  @if $color-mode-type == "media-query" {
    @if $root == true {
      @media (prefers-color-scheme: $mode) {
        :root {
          @content;
        }
      }
    } @else {
      @media (prefers-color-scheme: $mode) {
        @content;
      }
    }
  } @else if $color-mode-type == "data" {
    [data-cx-theme="#{$mode}"] {
      @content;
    }
  } @else {
    $theme: '[data-cx-theme="#{$mode}"]';
    $parent: &;
    // The mode that a theme of a nearer element can set against `$mode`
    $other: null;

    @if $mode == dark {
      $other: light;
    } @else if $mode == light {
      $other: dark;
    }

    @if $parent {
      // Inside a rule: the element has the theme, or is inside it with no
      // theme of the other mode in between
      $inside: ":where(#{$theme} *)";

      @if $other {
        $inside: $inside + ':not(:where(#{$theme} [data-cx-theme="#{$other}"] *))';
      }

      @at-root #{list.join(-subjects($parent, $theme), -subjects($parent, $inside), comma)} {
        @content;
      }

      @if $other {
        $no-other: ':not(:where([data-cx-theme="#{$other}"], [data-cx-theme="#{$other}"] *))';

        @media (prefers-color-scheme: $mode) {
          @at-root #{-subjects($parent, $no-other)} {
            @content;
          }
        }
      }
    } @else {
      #{$theme} {
        @content;
      }

      @if $other {
        // `:where()` keeps the weight of `:root`, so a declaration here and one
        // of a project's own `:root` rule are decided by their order
        @media (prefers-color-scheme: $mode) {
          :root:where(:not([data-cx-theme="#{$other}"])) {
            @content;
          }
        }
      }
    }
  }
}