Can you make feature detection for CSS?

6

I know the feature detection ("discovery of functionality") technique - as well as feature inference - when it comes to JavaScript:

if ( window.XMLHttpRequest ) { ... }

But how can you do this for CSS too? For example from this other question , I would like to create an animated menu only with CSS , but the transition property is not universally supported . I could do everything with jQuery, but it seems a waste to me since most browsers support this functionality.

The ideal would then be to detect if there is such support, using jQuery as fallback if there is none. It's possible? And if the answer is "no", is this one of the rare cases where browser detection is warranted?     

asked by anonymous 27.08.2014 / 16:13

1 answer

8

Yes, you can do CSS feature-detection, either using JavaScript or pure CSS (in this case you have your own cross-browser support issues).

By JavaScript, you simply check the style object of an element that has the property or value in question applied. For example, if your browser supports CSS transitions, the transition property of the object will have a value other than undefined . For more accuracy in checking, be sure to also check the prefixed variants, such as -moz-transition (the JavaScript property in this case would be MozTransition ).

This MDN example checks to see if the browser supports the property animation , checking for a elm element:

var animation = false,
    animationstring = 'animation',
    keyframeprefix = '',
    domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
    pfx  = '';

if( elm.style.animationName !== undefined ) { animation = true; }    

if( animation === false ) {
  for( var i = 0; i < domPrefixes.length; i++ ) {
    if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
      pfx = domPrefixes[ i ];
      animationstring = pfx + 'Animation';
      keyframeprefix = '-' + pfx.toLowerCase() + '-';
      animation = true;
      break;
    }
  }
}

With pure CSS, @supports works as a < in> media query . However, @supports support is limited . Another example of MDN:

@supports ( not ((text-align-last:justify) or (-moz-text-align-last:justify) ){
    … /* specific CSS applied to simulate text-align-last:justify */
}

It's good to remember that the Modernizr library uses these two techniques internally, and offers practical shortcuts to verify support for various CSS properties.

    
27.08.2014 / 16:37