Skip to main content

Command Palette

Search for a command to run...

@supports API

Check if a CSS feature is ready in a browser or not and apply code for both scenarios

Updated
2 min read
@supports API

In order to check if some CSS property is supported in a browser or not we can make use of the @supports API which itself is supported by all browsers except IE and Opera Mini (https://caniuse.com/css-supports-api) - so we’re good here.

So let take one good example of a CSS feature that many front-end developers have been waiting for.

It looks like grid-template-rows: masonry; may come to browsers this year. The latest Safari Technical Preview seems to have support for this though I couldn’t get it to work on my Safari Tech Preview on my macOS Sequoia 15.7.3 - not sure if masonry support is only for Tahoe’s version of Safari Tech Preview.

To check if your browser supports grid-template-rows: masonry we can use it in CSS like this :

@supports (grid-template-rows: masonry)
{

}

We can place any CSS within the block and the good part is we can also apply CSS to browsers that don’t support grid-template-rows: masonry - by using the not keyword.

@supports not (grid-template-rows: masonry)
{

}

You can get Firefox to support grid-template-rows: masonry by enabling layout.css.grid-template-masonry-value.enabled to true in about:config.

Here’s the sample CSS code :

.container
{
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    grid-template-rows: masonry;
}

.container > div
{      
    padding: 1em;
    background-color: #f0f0f0;
}

@supports (grid-template-rows: masonry)
{
    .container > div
    {
        border: 2px solid red;
    }
}

@supports not (grid-template-rows: masonry)
{
    .container > div
    {
        border: 2px solid green;
    }  
}

And here’s the corresponding HTML:

<div class="container">
    <div>Item 1</div>
    <div>Item 2.1<br/>Item 2.2</div>
    <div>Item 3.1<br/>Item 3.2<br/>Item 3.3</div>
    <div>Item 4</div>
</div>

This will show like this for no masonry support :

And like this for browsers that do support masonry :

Notice the difference - for one: the colours are different - and most importantly, the layout is as per the height of the content of each item cell and not uniform.

Demo : https://anjanesh.s3.us-east-1.amazonaws.com/demo/supports.html

Reference : https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Grid_layout/Masonry_layout