Skip to content

Instantly share code, notes, and snippets.

@motss
Created December 15, 2016 05:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save motss/cb65fd2034b6937c4cfd0264fc458cf6 to your computer and use it in GitHub Desktop.
Feature detection for Native CSS Properties aka CSS Custom Variables
// 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.
el.style.setProperty('--test-opacity', opacity);
el.style.setProperty('opacity', 'var(--test-opacity)');
// Feature detect then remove all set properties.
hasNativeCSSProperties = window.getComputedStyle(el).opacity == opacity;
el.style.setProperty('--test-opacity', '');
el.style.opacity = '';
return hasNativeCSSProperties;
}
hasNativeCSSProperties();
@tobireif
Copy link

Thanks! My version:

function supportsCssVariables() {

  var opacity = 1;
  var el = document.body;
  var result = false;

  // Setup CSS properties:
  el.style.setProperty('--test-opacity', opacity);
  el.style.setProperty('opacity', 'var(--test-opacity)');

  // Feature-detection:
  result = window.getComputedStyle(el).opacity == opacity;

  // Remove the set properties:
  el.style.setProperty('--test-opacity', '');
  el.style.opacity = '';

  // Plus "window.CSS" for IE11:
  return result && window.CSS;

}

@yukulele
Copy link

1 is the default value for opacity.
so window.getComputedStyle(document.body).opacity give 1 even if css variables are'n supported
you should test it with other value like 0.5 or other property like z-index

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