Feature Detection with @supports

With the help of the CSS @supports at-rule, you can quickly perform feature queries. 

The most popular feature query tool was Modernizr which do an amazing work nowadays too. The @supports rule achieves similar result but in a little bit different way.

Modernizr has attached the supported or non-supported classes to the HTML element, and you could style your content according to that. Modernizr is a JavaScript library, so in the most cases, you had to calculate with some flashing at the first render.

The declaration of this directive is similar to the @media queries. You can open a code block with necessary conditions. If the condition(s) is correct, the code block evaluates like in a responsive width media query.

Basic usage

At declaration, you must use property-value pairs enclosed in parenthesis. You can connect increased expression (in parentheses) with the logical operators.

@supports (property: value) {
    /* more styles */
}
@supports (position: sticky) {
    /* more styles */
}
Position: sticky; – Sticky is a quite new position value. It helps you stick your elements to stick at the top of their container. It is quite like the mix of fixed and relative position depending on the item position.

Nice to know that you can also check prefixed values like -webkit or -moz too!

Usable keywords

You can use the following logical keywords:

  • not operator to negating the following expression,
  • or and and operator for connecting expressions.
@supports not (position: sticky) {
    /* more styles */
}
@supports (position: sticky) and ( filter: blur(2px) ) {
    /* more styles */
}

Supports from JavaScript

You can also use this feature detection technique from JS. With the help of the CSS object supports method you can test different declaration like you do in CSS.

The simple way for the check is when you give one property and one value like the following:

var supportsSticky = CSS.supports('position', 'sticky');

You can also check more complex checks if you use string as your value:

var supportsStickyAndFilter = CSS.supports('(position: sticky) and (filter: blur(5px))');

Example

In this example we check the sticky position value. If it is not supported we are making a simple fallback.

See the Pen gWzpOE by Adam Laki (@adamlaki) on CodePen.

Summary

Today you can courageously use the @support in all modern browser. Thanks for the JS API you can also drop Modenizr for feature query tasks. With the evolving CSS features, it can be handy that you can also check for a particular value.

Keep in your mind that you can use it for your next project!

Special thanks for the following recource(s): Icon made by dDara from www.flaticon.com