Detect Browser CSS Support With @supports Rule

Since browsers have their own decision of what features to include, we web developers frequently have to identify if the browser supports particular features, then we fill in the gap using Polyfills (if required). The popular way of handling this kind of situation is by using Modernizr but do you know that we can also do this using only CSS?

There is a new rule being formulated in W3C Draft, called @supports. In this post, we will walk you through on how this rule works to let you detect browser features via CSS.

Using @support rule

Unlike Modernizr, the @supports rule requires property and the value specified. Let’s say we want to apply CSS3 grid only to the browser that supports it. We can write it this way.

 @support (display: grid;) { .selector { display: grid; grid-column: 3; grid-row: 1; grid-row-span: 2; } }

The CSS rules under the @support will only be applied if the condition returns true. Given the above example, it will be applied if the browser supports display: grid. Or else, the browsers will apply other equivalent rules outside @support.

Mixing Conditions

Furthermore, we are allowed to combine multiple conditions using and, or, and not operator. For example, let’s say we want to apply rules only if the browser meets the following conditions:

  • It supports either CSS3 Grid or CSS3 Flexbox.
  • It supports CSS3 Columns.

In that case, we can write the conditional rules, as follows.

 @support ((display: grid;) or (display:flexbox;)) and (column-count:3;) { /* Your CSS rules here */ }

Remember that if you include multiple operators in a single rule set, each operator should be grouped in parentheses as we have shown you above.

Writing it in the following way is invalid, and will confuse the browser.

 @support (display: grid;) or (display:flexbox;) and (column-count:3;) { /* Your CSS rules here */ }

Final Thought

This feature is great and would be very useful on several occasions.

In order for the tests, however, the browsers have to support this rule; otherwise this method will fail. And at the time of this writing, Opera seems to be the only browser that has implemented this feature. So, until the spec is stable and has been covered by all other browsers, delay using this method to test during the production stages. For experiments though, go all out.

Further Resource