Is there any way to Feature Detection for CSS?

Asked

Viewed 99 times

6

I know the technique of Feature Detection ("functionality discovery") - as well as Feature inference - when it comes to Javascript:

if ( window.XMLHttpRequest ) { ... }

But can you do this for CSS as well? For example of that other question, i would like to create an animated menu CSS-only, but the property transition is not universally supported. I could do everything with jQuery, but it seems a waste since the vast majority of browsers supports this functionality.

The ideal then would be to detect if there is such support, using jQuery as fallback if not. Is it possible? And if the answer is "no", this would be one of the rare cases where browser Detection is justified?

1 answer

8


Yes, you can do CSS Feature-Detection, both using Javascript and with pure CSS (in this case you have your own cross-browser support issues).

By Javascript, you simply check the object style of an element that has the property or value in question applied. For example, if the browser supports CSS transitions, the property transition object will have a value different from 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 example of MDN checks if the browser supports the property animation, by checking an element elm:

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, there is the @supports that functions as a media query. However, the support for @supports 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 library Modernizr uses these two techniques internally, and offers practical shortcuts to check support for various CSS properties.

  • +Note 100 for this pair P&R+ . . . Meanwhile

  • 1

    Yo Dawg, I Herd you like to test for support using @supports, only I created a suportaSupports so you can test for @supports support to use @supports to test for support. (tested in Chrome and IE)

  • 1

    a detail, I followed the other topic.... the library of the site that the boy uses as example menu that he wanted to do, also uses the library Moderniz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.