Feature Detection With @supports CSS Rule

CSS is updating day by day and lot of new features are being added .How and when a new feature is implemented is decided by the browser and sometimes we use their vendor prefix like “-moz” , “-webkit” , “-o” , “-ms”.

The problem designers face is how to check whether the new CSS feature will be supported in the browser or not.So to overcome this problem W3C has made a new specification for a @supports CSS rule.

The @supports CSS rule allows you to perform feature detection in the browser right from your style sheet so you don’t have to use third party resources like modernizr. You can use @supports to test a css condition and then place the css rules inside the block so it will work if its supported.

Lets have a look at basic example.


@supports (display: flex) {
	div { display: flex; }
}

This will apply the display property with value flex to div if the browser supports it.

The Not Operator

The not operator can be used to check no support


@supports not (display: flex) {
	div { float: left; }
}

Multiple Condition Check with and|or Operators

We can also combine multiple conditons using and|or operators.For example you can use and operator to check to conditions or combine both and|or even with not operator.The conditions can be wrapped in parenthesis just like we do in other programming languages.


@supports ((display: -webkit-flex) or
          (display: -moz-flex) or
          (display: flex)) and (-webkit-appearance: caret) {

    /* use styles here */
}

Best Practices and Notes

  • Whitespace is required after a not and on both sides of an and|or.
  • The property to be tested must be placed within parentheses.
  • If you combine the not operator with the other operators, there is no need to enclose the not between two parenthesis when it is at the top level. Parantheses are required, however, if it is not the first condition in the declaration.
  • 
    @supports display: flex {   
      /* property to be tested is not inside parenthesis */
    }
    /* INVALID because parenthesis are not present before not */
    @supports (...) or (...) not (...) { /* ... */ }
    
    

    The best usage of @supports is setting an older set of styles as backup and then overriding those styles or enhancing them if a given property is supported.The new flex display is very useful but supported by limited browsers so lets check it.

    
    section {
    	float: left;
    }
    
    @supports (display: -webkit-flex) or
              (display: -moz-flex) or
              (display: flex) {
    
        section {
          display: -webkit-flex;
          display: -moz-flex;
        	display: flex;
        	float: none;
        }
    }
    
    

    @supports Browser Support

    The @supports is a newly added feature and will be enhanced in the near future . Its only supported by modern edge browsers.