Skip to content

Instantly share code, notes, and snippets.

Last active August 11, 2021 14:23
Show Gist options
  • Save wesbos/8b9a22adc1f60336a699 to your computer and use it in GitHub Desktop.
Save wesbos/8b9a22adc1f60336a699 to your computer and use it in GitHub Desktop.
Test for CSS Variables
function testCSSVariables() {
var color = 'rgb(255, 198, 0)';
var el = document.createElement('span');'--color', color);'background', 'var(--color)');
var styles = getComputedStyle(el);
var doesSupport = styles.backgroundColor === color;
return doesSupport;
Copy link

Nice one Wes, thank for help with that. I'm going to mention your way in my future article (in progress). Thanks a lot again!

Copy link

Shouldn't be the following test reliable enough to detect CSS custom property support? Or am I missing something?

if (window.CSS && window.CSS.supports && window.CSS.supports('--a', 0)) {
  // CSS custom properties supported.
} else {
  // CSS custom properties not supported

Copy link

motss commented Dec 15, 2016

@justmarkup Your snippet does not guarantee to work. Safari 10 fails to return true.

Copy link

motss commented Dec 15, 2016

This is my version: hasNativeCSSProperties:

// Not too sure if it will trigger layout and paint for other CSS properties.
// I just use opacity which only triggers composite by default!
function hasNativeCSSProperties() {
 const opacity = 1;
 const el = document.body;
 let hasNativeCSSProperties = false;

 // Setup CSS properties.'--test-opacity', opacity);'opacity', 'var(--test-opacity)');

 // Feature detect then remove all set properties.
 hasNativeCSSProperties = window.getComputedStyle(el).opacity == opacity;'--test-opacity', ''); = '';
 return hasNativeCSSProperties;


Copy link

window.CSS.supports still fails in Saf 😆

Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment