šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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
}

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *