Search code examples
javascriptcssmodernizrfeature-detectioncss-variables

How to feature detect for CSS custom properties?


Is there any way to detect whether a browser supports CSS custom properties (eg. color: var(--primary))?

I need to write a script that behaves slightly differently in browsers that don't support custom properties, but I can't find any documented Modernizr tests, nor any information about the Javascript interface for accessing custom properties.

Would be grateful for any suggestions!


Solution

  • You can reliably use CSS.supports() in JavaScript or @supports in CSS to detect support for custom properties. Every version of every browser that supports custom properties also supports this method of feature detection.

    if (window.CSS && CSS.supports('color', 'var(--primary)')) {
      document.body.innerHTML = 'Supported';
    }
    @supports (color: var(--primary)) {
      body {
        background-color: green;
      }
    }

    Notice that this does not require you to declare the --primary custom property, as by definition every property whose name begins with -- is considered valid for the purposes of parsing property declarations.