IE11 - does a polyfill / script exist for CSS variables?

R. StackUser picture R. StackUser · Sep 26, 2017 · Viewed 73.1k times · Source

I'm developing a webpage in a mixed web browser environment (Chrome/IE11). IE11 doesn't support CSS variables, is there a polyfill or script that exists that would allow me to use CSS variables in IE11?

Answer

jhildenbiddle picture jhildenbiddle · Mar 10, 2018

Yes, so long as you're processing root-level custom properties (IE9+).

From the README:

Features

  • Client-side transformation of CSS custom properties to static values
  • Live updates of runtime values in both modern and legacy browsers
  • Transforms <link>, <style>, and @import CSS
  • Transforms relative url() paths to absolute URLs
  • Supports chained and nested var() functions
  • Supports var() function fallback values
  • Supports web components / shadow DOM CSS
  • Watch mode auto-updates on <link> and <style> changes
  • UMD and ES6 module available
  • TypeScript definitions included
  • Lightweight (6k min+gzip) and dependency-free

Limitations

  • Custom property support is limited to :root and :host declarations
  • The use of var() is limited to property values (per W3C specification)

Here are a few examples of what the library can handle:

Root-level custom properties

:root {
    --a: red;
}

p {
    color: var(--a);
}

Chained custom properties

:root {
    --a: var(--b);
    --b: var(--c);
    --c: red;
}

p {
    color: var(--a);
}

Nested custom properties

:root {
    --a: 1em;
    --b: 2;
}

p {
    font-size: calc(var(--a) * var(--b));
}

Fallback values

p {
    font-size: var(--a, 1rem);
    color: var(--b, var(--c, var(--d, red))); 
}

Transforms <link>, <style>, and @import CSS

<link rel="stylesheet" href="/absolute/path/to/style.css">
<link rel="stylesheet" href="../relative/path/to/style.css">

<style>
    @import "/absolute/path/to/style.css";
    @import "../relative/path/to/style.css";
</style>

Transforms web components / shadow DOM

<custom-element>
  #shadow-root
    <style>
      .my-custom-element {
        color: var(--test-color);
      }
    </style>
    <div class="my-custom-element">Hello.</div>
</custom-element>

For the sake of completeness: w3c specs

Hope this helps.

(Shameless self-promotion: Check)