Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

postcss-css-variables

MadLittleMods1mMIT0.19.0TypeScript support: definitely-typed

PostCSS plugin to transform CSS Custom Properties(CSS variables) syntax into a static representation

postcss, css, postcss-plugin

readme

PostCSS CSS Variables

npm version Build Status Gitter

PostCSS plugin to transform CSS Custom Properties (CSS variables) syntax into a static representation. This plugin provides a future-proof way of using most of CSS variables features, including selector cascading with some caveats, because this can only see the CSS, not the potentially dynamic HTML and DOM the CSS is applied to.

Install

npm install postcss postcss-css-variables --save-dev

Table of Contents

Code Playground

Try it in the playground and see what you think! Just add some CSS and see to see the final transformed/compiled CSS. You can try anything here in the playground, too.

Usage

For more general PostCSS usage, look here.

var postcss = require("postcss");
var cssvariables = require("postcss-css-variables");

var fs = require("fs");

var mycss = fs.readFileSync("input.css", "utf8");

// Process your CSS with postcss-css-variables
var output = postcss([cssvariables(/*options*/)]).process(mycss).css;

console.log(output);

Syntax

Defining Custom Properties with --*

A custom property is any property whose name starts with two dashes --. A property must be in a rule.

Note: :root is nothing more than the selector for the root DOM node. Any other selector like .class, #id, or even #foo ~ .bar > span.baz works.

:root {
  --foo-width: 100px;
  --foo-bg-color: rgba(255, 0, 0, 0.85);
}

.foo {
  --foo-width: 100px;
  --foo-bg-color: rgba(255, 0, 0, 0.85);
}

Custom properties can be declared multiple times, but like variable scope in other languages, only the most specific one takes precedence.

:root {
  --some-color: red;
}

.foo {
  /* red */
  color: var(--some-color);
}

.bar {
  --some-color: blue;
  /* blue */
  color: var(--some-color);
}

.bar:hover {
  --some-color: green;
  /* Automatically gets a `color: green;` declaration because we `--some-color` used within scope elsewhere */
}

W3C Draft: CSS Custom Properties for Cascading Variables, section 2

Using Variables/Custom Properties with var()

.foo {
  width: var(--foo-width);
  /* You can even provide a fallback */
  background: var(--foo-bg-color, #ff0000);
}

W3C Draft: CSS Custom Properties for Cascading Variables, section 3

Features

At-rules like @media, @support, etc.

It's perfectly okay to declare CSS variables inside media queries and the like. It'll work just as you would expect.

:root {
  --width: 100px;
}

@media (max-width: 1000px) {
  :root {
    --width: 200px;
  }
}

.box {
  width: var(--width);
}

Will be transformed to:

.box {
  width: 100px;
}

@media (max-width: 1000px) {
  .box {
    width: 200px;
  }
}

Pseudo-classes and Elements

Psuedo-classes are also dealt with correctly, because it's easy to statically determine.

.foo {
  --foo-color: red;
  color: var(--foo-color);
}

.foo:hover {
  --foo-color: green;
}

Will be transformed to:

.foo {
  color: red;
}

.foo:hover {
  color: green;
}

Nested Rules

This pairs very well with postcss-nested or postcss-nesting, adding support for nested rules. For either, you must put the plugin before postcss-css-variables in the plugin stack so that the & references are expanded first (postcss-css-variables doesn't understand them). For example, with postcss-nested, your PostCSS setup would look like this:

var postcss = require("postcss");
var cssvariables = require("postcss-css-variables");
var nested = require("postcss-nested");

var fs = require("fs");

var mycss = fs.readFileSync("input.css", "utf8");

var output = postcss([
  // Flatten/unnest rules
  nested,
  // Then process any CSS variables
  cssvariables(/*options*/)
]).process(mycss).css;

console.log(output);

For a simple example with nesting:

.box-foo {
  --some-width: 150px;
  width: var(--some-width);

  .box-bar {
    width: var(--some-width);
  }
}

With also postcss-nesting, this will be transformed to:

.box-foo {
  width: 150px;
}

.box-foo .box-bar {
  width: 150px;
}

For a more complex example with a media query:

:root {
  --some-width: 150px;
}

.box-foo {
  width: var(--some-width);

  .box-bar {
    width: var(--some-width);
  }
}

@media (max-width: 800px) {
  .box-foo {
    --some-width: 300px;
  }
}

Will be transformed to:

.box-foo {
  width: 150px;
}

.box-foo .box-bar {
  width: 150px;
}

@media (max-width: 800px) {
  .box-foo {
    width: 300px;
  }

  .box-foo .box-bar {
    width: 300px;
  }
}

Why?

This plugin was spawned out of a discussion on the cssnext repo and a personal need.

There is another similar plugin available, postcss-custom-properties, although it restricts itself much more than this plugin, preferring partial spec conformance. This plugin has the same capabilities but also adds imperfect feature support which stem from not being able to know what the DOM will look like when you compile your CSS. We instead look at the explicit structure of your CSS selectors.

Interoperability and differences from postcss-custom-properties

Putting postcss-css-variables in place of postcss-custom-properties should work out of the box.

In postcss-custom-properties, CSS variable declarations are specifically restricted to the :root selector.

In postcss-css-variables, this is not the case and they may be declared inside any rule with whatever selector. The variables are substituted based on statically known CSS selector inheritance.

Here's a quick overview of the differences:

  • CSS variables may be declared in any selector like .foo or .foo .bar:hover, and is not limited to just :root
  • CSS variables may be declared in @media, @support, and other at-rules.
  • CSS variables may be declared in :hover and other psuedo-classes, which get expanded properly.
  • Variables in nested rules can be deduced with the help of postcss-nested or postcss-nesting.

Continue to the next section to see where some of these might be unsafe to do. There are reasons behind the ethos of why the other plugin, postcss-custom-properties, is very limited in what it supports, due to differing opinions on what is okay to support.

Caveats

When you declare a CSS variable inside one selector, but consume it in another, this does make an unsafe assumption about it which can be non-conforming in certain edge cases. Here is an example where these limitations result in non-conforming behavior.

Note the nested markup below. We only know about the DOM's inheritance from your CSS selectors. If you want nest multiple times, you need to be explicit about it in your CSS which isn't necessary with browser that natively support CSS variables. See the innermost <div class="title">

<div class="component">
  Black

  <div class="title">
    Blue

    <div class="decoration">
      Green

      <div class="title">Blue with this plugin, but green per spec</div>
    </div>
  </div>
</div>
.component {
  --text-color: blue;
}

.component .title {
  color: var(--text-color);
}

.component .decoration {
  --text-color: green;
  color: var(--text-color);
}

postcss-custom-properties avoids this problem entirely by restricting itself to just the :root selector. This is because the developers there would prefer to not support a feature instead of something almost-spec-compliant like what postcss-css-variables does.

Options

preserve (default: false)

Allows you to preserve custom properties & var() usage in output.

Possible values:

  • false: Removes --var declarations and replaces var() with their resolved/computed values.
  • true: Keeps var() declarations in the output and has the computed value as a fallback declaration. Also keeps computed --var declarations.
  • 'computed': Keeps computed --var declarations in the output. Handy to make them available to your JavaScript.
  • (declaration) => boolean|'computed' : function/callback to programmatically return whether preserve the respective declaration

variables (default: {})

Define an object map of variables in JavaScript that will be declared at the :root scope.

Can be a simple key-value pair or an object with a value property and an optional isImportant bool property.

The object keys are automatically prefixed with -- (according to CSS custom property syntax) if you do not provide it.

preserveInjectedVariables (default: true)

Whether to preserve the custom property declarations inserted via the variables option from final output.

A typical use case is CSS Modules, where you would want to avoid repeating custom property definitions in every module passed through this plugin. Setting this option to false prevents JS-injected variables from appearing in output CSS.

var postcss = require("postcss");
var cssvariables = require("postcss-css-variables");

postcss([
  cssvariables({
    variables: {
      "--some-var": "100px",
      "--other-var": {
        value: "#00ff00"
      },
      "--important-var": {
        value: "#ff0000",
        isImportant: true
      }
    }
  })
]).process(css, opts);

preserveAtRulesOrder (default: false)

Keeps your at-rules like media queries in the order to defined them.

Ideally, this would be defaulted to true and it will be in the next major version. All of the tests expecations need to be updated and probably just drop support for preserveAtRulesOrder: false

Quick Reference/Notes

Testing

We have a suite of Mocha tests. If you see something that doesn't have coverage, make an issue or pull request.

Run once:

npm install

Run whenever you want to test:

npm run test

changelog

v0.19.0 - 2023-04-12

v0.18.0 - 2021-05-11

  • [breaking] Add basic postcss 8 support (older versions of PostCSS no longer compatible)

v0.17.0 - 2020-04-24

v0.16.0 - 2020-04-24

  • Add ability to pass callback function to options.preserve to determine whether to preserve declaration

v0.15.0 - 2020-04-24

  • Fix algorithm to find balanced var() pairs and nested parenthesis

v0.14.0 - 2019-11-24

v0.13.0 - 2019-06-17

v0.12.0 - 2019-02-21

v0.11.0 - 2018-10-09

v0.10.0 - 2018-09-25

v0.9.0 - 2018-06-26

  • Adds opts.preserveInjectedVariables, which when set to false, removes the :root { ... } custom property declarations added via opts.variables

v0.8.1 - 2018-03-21

v0.8.0 - 2017-08-08

v0.7.0 - 2017-03-12

v0.6.0 - 2016-09-23

v0.5.2 - 2016-08-24

v0.5.1 - 2015-10-24

  • Fix postcss/postcss#611 where we were trying to remove the root node on clean up
  • Improved test setup

v0.5.0 - 2015-09-12

  • Upgrade to PostCSS v5. Fix #20

v0.4.0 - 2015-07-02

  • Fix #15 - Remove slowness from cloning the root with node.clone().removeAll(). Now using ./lib/shallow-clone-node.js to avoid cloning children which will get removed right after. - Thank you to @ddprrt for bringing up the slowness issue in this article, PostCSS misconceptions.

v0.3.9 - 2015-06-29

  • Remove opts global leak. Fix #13

v0.3.8 - 2015-05-28

  • Add support for pseudo selectors :hover :before

v0.3.7 - 2015-05-27

  • Fix #7: Support for child combinator
  • Added tests for child-combinator/direct-descendant coverage

v0.3.6 - 2015-05-21

  • Fix #6. Variable usage in comma separated selector to use proper scope

v0.3.5 - 2015-05-12

  • Big refactor of code to reduce cyclomatic complexity. Still needs work though.
  • Fix variable referencing another variable resolution when being changed by at-rule in non-root rule

v0.3.4 - 2015-05-12

  • Fix variable referencing another variable resolution when being changed by at-rule

v0.3.3 - 2015-05-11

  • Add support for last piece of combinator chain in selector resolution matching. - .foo + .bar can match variables declared in .bar

v0.3.1 - 2015-05-05

v0.2.3 - 2015-05-04

  • Add support for CSS4 descendant selector >> syntax

v0.2.2 - 2015-05-01

  • Automatically prefix any variables defined in options.variables with -- (according to CSS custom property syntax).

v0.2.1 - 2015-04-30

  • Added support for descendant selector nesting instead of just physical space nesting
  • Fixed issue with comma separated rules. It was throwing a undefined is not a function error
  • Moved to external scope check isUnderScope instead of integrated into resolveValue
  • Added test for empty var() call. See test/fixtures/empty-var-func.css

v0.1.0 - 2015-04-29

  • First release