An introduction to @supports

The @supports rule in CSS is used to apply styles only if the browser supports specific CSS features. This is helpful for ensuring that your styles are compatible with the capabilities of the user’s browser, allowing you to provide fallbacks or enhanced styles based on the presence of certain CSS properties or values.


Basic Usage


The @supports rule takes a condition that checks for support of a particular CSS feature. If the condition is true, the styles inside the @supports block will be applied.


Example

Let's say you want to use the CSS Grid layout but only if the browser supports it. You can use @supports to check for this feature:

@supports (display: grid) {
    .container {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
    }
}


@supports not (display: grid) {
    .container {
        display: flex;
        flex-wrap: wrap;
    }
    .container > div {
        flex: 1 0 30%;
        margin: 5px;
    }
}


Explanation

  • Check for Grid Support: The @supports (display: grid) block checks if the browser supports CSS Grid. If it does, the styles inside this block will be applied, setting up a grid layout with three equal columns and a 10px gap between them.
  • Fallback for Non-Supporting Browsers: The @supports not (display: grid) block provides a fallback for browsers that do not support CSS Grid. In this case, it uses Flexbox to create a responsive layout with wrapping elements and margins.


Advanced Usage


You can also use logical operators such as and, or, and not within the @supports rule to combine multiple conditions.


Example with Multiple Conditions

@supports (display: grid) and (gap: 10px) {
    .container {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;
    }
}


@supports (display: flex) and not (gap: 10px) {
    .container {
        display: flex;
        flex-wrap: wrap;
    }
    .container > div {
        flex: 1 0 30%;
        margin: 5px;
    }
}


Explanation

  • Combined Conditions: The @supports (display: grid) and (gap: 10px) block applies styles only if both conditions (support for display: grid and gap: 10px) are met.
  • Mixed Conditions: The @supports (display: flex) and not (gap: 10px) block applies styles if display: flex is supported but gap: 10px is not.


Using @supports helps you write more robust and adaptable CSS by allowing you to tailor your styles to the capabilities of the user's browser.