How to define a property for custom CSS properties?

Is it possible to determine if the browser supports custom CSS properties (e.g. color: var(--primary))?

I need to write a script that behaves somewhat differently in browsers that do not support user-defined properties, but I cannot find the documented Modernizr , nor any Javascript interface information to access the user-defined properties.

I would be grateful for any suggestions!

+4
source share
2 answers

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

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

Note that this does not require the declaration of a custom property --primary, as by definition each property whose name begins with --is considered valid for parsing property declarations.

+11
source

I will leave this as an example of how to approach similar things when you have no alternative, but BoltClock's answer is the way to go in this case.


, , , getComputedStyle. , Supports custom props? true Chrome ( CSS), Supports custom props? false IE11 ( ):

function areCSSVarsSupported() {
  var d = document.createElement('div');
  d.id = "test";
  document.body.appendChild(d);
  var pos = getComputedStyle(d).position;
  document.body.removeChild(d);
  return pos === "fixed";
}
console.log("Supports custom props? " + areCSSVarsSupported());
:root{
  --test-vars: fixed;
}

#test {
  position: var(--test-vars);
}
Hide result
+1

All Articles