Checkout my Getting Started with React video course on Skillshare. It is 100% free.

The CSS @supports property: logical operators, fallback values, and the Javascript API

There is a constant stream of new shiny features released in CSS, some of them not fully supported across all the browsers. To detect if the client's browser supports a specific CSS feature the simplest way is to use the @supports query.

@supports(display: grid) {
    .parent {
        display: grid
    }
}

We can use it even with logical operators like conjunctions (the and operator) or disjunctions (the or operator).

@supports(display: tabel) and (display: table-header) {
    .table-element {
        // add stuff here
    }
}
How can I provide a fallback value for if my CSS property is not supported

Even if we have and or operators we don't have yet access to an if ... else supports structure in CSS. However, we can simulate it in two ways.

The first one is to take advantage of the cascading rules in CSS.

.my-red-transparent-div {
    background: red;
    background: rgba(255, 0, 0, .5);
}

How this will work is that CSS will apply the latest rules it will understand. In the above case if the browser does not yet support rgba it will just ignore the second line and will apply the last declaration it understands, in this case background: red;

If it knows about rgba then the second line will become the last understood declaration and therefore background: rgba(255, 0, 0, .5); will be applied.

The second approach is to use the not logical operator:

@supports (background: rgba(255, 0, 0, .5)) {
    .my-red-transparent-div {
        background: rgba(255, 0, 0, .5);
    }
}

@supports not (background: rgba(255, 0, 0, .5)) {
    .my-red-transparent-div {
        /*just make the div red*/
        background: rgba(255, 0, 0);
    }
}
Detecting the CSS supports Javascript API

There is also a Javascript API for CSS supports. You will need to pass it the CSS property name and value and it will return true or false based on what the client's browser supports:

if(CSS.supports('display', 'table-header')) { 
    // add code here
}
Home Screencasts Best of Newsletter Search X