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!
To define a custom property, use the name of your choice preceded by two dashes, for example: --my-property . Then you can use that value by calling it within the var() CSS function in place of providing a standard value.
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.
Syntax of the var() Function The var() function is used to insert the value of a CSS variable. Note: The variable name must begin with two dashes (--) and it is case sensitive!
To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.
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.
I'll leave this as an example of how to approach this sort of thing when you don't have an alternative, but BoltClock's answer is the way to go in this case.
I expect you could define one and then check whether its value comes through to getComputedStyle
. For instance, this shows Supports custom props? true
on Chrome (which supports custom CSS properties) but Supports custom props? false
on IE11 (which doesn't):
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With