Search code examples
javascriptcssbrowserfeature-detection

How to check if a CSS property or value is supported by a browser?


My div that uses vh is not working in some browsers, so I want to check if it is supported. I found this article by Lea Verou on the subject, but I'm really not sure how to use it with a CSS value:

Here is the code given as a shortcut for you:

if('opacity' in document.body.style) {  
   // do stuff
}

function isPropertySupported(property{
   return property in document.body.style;
 }

In the comments of the article above someone asks how to check if a CSS value is supported and the answer is, "You set it, then read the value back and check if the browser retained it." which sounds like requires JavaScript (which I don't know).

How can I check in CSS or in JavaScript whether a property or a value is supported by a browser?


Solution

  • I assume you meant to check whether the vh value is supported, not whether specifically DIV#id bears it?

    function cssPropertyValueSupported(prop, value) {
      var d = document.createElement('div');
      d.style[prop] = value;
      return d.style[prop] === value;
    }
    cssPropertyValueSupported('width', '1px');
    // => true
    cssPropertyValueSupported('width', '1vh');
    // => maybe true, maybe false (true for me)
    cssPropertyValueSupported('width', '1foobar');
    // => false
    

    EDIT: This is obsolete; CSS.supports is now well supported, and should be used instead. Please support this answer instead.