How to check for CSS3 browser support

JavaScript polyfill, by , Wednesday, July 1st, 2015

Not all modern browsers support the same CSS3 features and sometimes you might want to take different paths through your style sheets depending on if a specific feature is supported or not. The Modernizr can be customized to make specific checks for you, and you can concentrate on writing your CSS, which is great. But being a developer it is also nice to know how this is done and how easy it actually is to make basic support checks.

This is by no means a complete guide to build your own Modernizr library, but rather a small simple introduction to how you fast, without the need to include yet another library in your code base, could make a few necessary checks. I will be using box-shadow as an example as it includes dealing with browser prefixes.

box-shadow browser support

All DOM elements have a style property which in modern browsers is an object with properties representing the supported styling properties. In other words, if we have a given element we can check if a given styling property is supported, which is exactly what we are going to do. Now this is very simple to do, but before we write the actual code, we need to consider browser prefixes. As we are going to use box-shadow as an example, we need to check for the following styles; WebkitBoxShadow and MozBoxShadow. You will probably see other prefixes such as msBoxShadow and OBoxShadow but according to Mozilla Developer within all reason that is not necessary. So we will stick with webkit and moz.

  1. // CSS3 box-shadow support
  2. var elm = document.createElement('test'),
  3. styleTypes = ['WebkitBoxShadow', 'MozBoxShadow', 'boxShadow'],
  4. i = 0;
  5.  
  6. for (;i < styleTypes.length; i++) {
  7. if (elm.style[styleTypes[i]] !== undefined) {
  8. document.documentElement.className += " boxshadow";
  9. }
  10. }

Basically what we do here is, that we iterate over our array of style properties, check if they exist on our created element test and if it does, we add the class boxshadow to the document element (HTML element for HTML documents). In this way, you can arrange your style sheets to add different effects depending on what the browser supports. It is as simple as that, and of course depending on which style property you want to check for, you will need different browser prefixes or in some cases none at all.

Thank you for reading, I hope it was useful and informative.