1.0.0 • Published 6 years ago

css-prefers-interface v1.0.0

Weekly downloads
5
License
CC0-1.0
Repository
github
Last release
6 years ago

CSS Prefers Interface

NPM Version Build Status Support Chat

CSS Prefers Interface lets you use “dark mode” media queries in CSS.

npm install css-prefers-interface
@media (--prefers-interface: dark) {
  :root {
    --site-bgcolor: #1b1b1b;
    --site-color: #fff;
  }
}

body {
  background-color: var(--site-bgcolor, #f9f9f9);
  color: var(--site-color, #111);
  font: 100%/1.5 system-ui;
}

PostCSS transforms these into cross-browser compatible color-index queries:

@media (color-index: 48) {
  :root {
    --site-bgcolor: #1b1b1b;
    --site-color: #fff;
  }
}

body {
  background-color: var(--site-bgcolor, #f9f9f9);
  color: var(--site-color, #111);
  font: 100%/1.5 system-ui;
}

CSS._prefersInterface() applies these “light mode” and “dark mode” queries to documents on the fly. The entire frontend script is less than 300 bytes.

CSS Prefers Interface works in all major browsers, including Safari 6+ and Internet Explorer 9+. See it for yourself.

import 'css-prefers-interface';

// apply "dark" queries
CSS._prefersInterface('dark');

// apply "light" queries (also disabling "dark" queries)
CSS._prefersInterface('light');

PostCSS Usage

Add CSS Prefers Interface to your project:

npm install css-prefers-interface --save-dev

Use CSS Prefers Interface to process your CSS:

import postcssPrefersInterface from 'css-prefers-interface/postcss';

postcssPrefersInterface.process(YOUR_CSS /*, processOptions, pluginOptions */);

Or use it as a PostCSS plugin:

import postcss from 'postcss';
import postcssPrefersInterface from 'css-prefers-interface/postcss';

postcss([
  postcssPrefersInterface(/* pluginOptions */)
]).process(YOUR_CSS /*, processOptions */);

CSS Prefers Interface runs in all Node environments, with special instructions for:

NodeWebpackCreate React AppGulpGrunt

How does the frontend work?

The color-index media query is understood in all major browsers going back to Internet Explorer 9, but all implementations only seem to allow a color-index of 0.

This script changes (color-index: 48) queries into not all and (color-index: 48) to activate “dark mode” specific CSS, and then it inverts (color-index: 70) queries into not all and (color-index: 48) to activate “light mode” specific CSS.

@media (color-index: 70) { /* "light" query */
  body {
    background-color: white;
    color: black;
  }
}

These valid queries are accessible to document.styleSheet, so no css parsing is required to use this library, which is how the script is less than 300 bytes.

Why does the frontend work this way?

The value of 48 is chosen for dark mode because it is the keycode for 0, the hexidecimal value of black. Likewise, 70 is chosen for light mode because it is the keycode for f, the hexidecimal value of white.