CSS custom properties polyfill for ie11

user973671 picture user973671 · Sep 26, 2017 · Viewed 17.7k times · Source

Is there a way to pollyfill a custom CSS property for ie11 with JavaScript? I was thinking on load, check if browser supports custom properties and if not do some kind of find and replace on the properties.

Is this possible with JavaScript or some library?

Thanks

Answer

Tobias Buschor picture Tobias Buschor · Jul 1, 2019

Have a look at this (my) Custom-Properties-Polyfill:
https://github.com/nuxodin/ie11CustomProperties

How it works

The script makes use of the fact that IE has minimal custom properties support where properties can be defined and read out with the cascade in mind.
.myEl {-ie-test:'aaa'} // only one dash allowed "-"
then read it in javascript:
getComputedStyle( querySelector('.myEl') )['-ie-test']

From the README:

Features

  • handles dynamic added html-content
  • handles dynamic added , -elements
  • chaining --bar:var(--foo)
  • fallback var(--color, blue)
  • :focus, :target, :hover
  • js-integration:
    • style.setProperty('--x','y')
    • style.getPropertyValue('--x')
    • getComputedStyle(el).getPropertyValue('--inherited')
  • Inline styles: <div ie-style="--color:blue"...
  • cascade works
  • inheritance works
  • under 3k (min+gzip) and dependency-free

Demo:

https://rawcdn.githack.com/nuxodin/ie11CustomProperties/b851ec2b6b8e336a78857b570d9c12a8526c9a91/test.html