How can I detect CSS Variable support with JavaScript? How can I detect CSS Variable support with JavaScript? javascript javascript

How can I detect CSS Variable support with JavaScript?


We can do this with CSS.supports. This is the JavaScript implementation of CSS's @supports rule which is currently available in Firefox, Chrome, Opera and Android Browser (see Can I Use...).

The CSS.supports() static methods returns a Boolean value indicating if the browser supports a given CSS feature, or not.
Mozilla Developer Network

With this, we can simply:

CSS.supports('color', 'var(--fake-var)');

The result of this will be true if the browser supports CSS variables, and false if it doesn't.

(You might think that CSS.supports('--fake-var', 0) would work, but as noted in comments on this answer Safari seems to have a bug there making it fail.)

Pure JavaScript Example

On Firefox this code snippet will produce a green background, as our CSS.supports call above returns true. In browsers which do not support CSS variables the background will be red.

var body = document.getElementsByTagName('body')[0];if (window.CSS && CSS.supports('color', 'var(--fake-var)')) {  body.style.background = 'green';} else {  body.style.background = 'red';}