Understanding CSS Feature Queries


What are Feature Queries?

Feature queries are a relatively new addition to CSS. They allow developers to scope styles to specific browser features, rather than browser versions. This is particularly useful for CSS features that are not yet fully supported by all browsers, or for which there is significant variation in implementation.

How do Feature Queries Work?

Feature queries are written using the @supports rule, which is part of the CSS Conditional Rules module. The @supports rule takes a condition as an argument and only applies the styles inside it if the condition is true.

Let’s take an example, The following @supports rule will only apply the styles if the browser supports the CSS transform property:

  .container {
    border: 4px solid red;
    color: red;
    padding: 10px;
  }
  @supports (transform: rotate(180deg)) {
    .container {
      border: 4px solid green;
      color: green;
    }
  }
  <div class="container">
    If the browser supports CSS transforms, the border 
    and text will be green.
  </div>

The condition can be any valid CSS expression but must be wrapped in parentheses.

Feature Queries and Prefixes

One of the most common uses for feature queries is to scope styles that require vendor prefixes to only browsers that need them. This can be particularly useful if a feature is vendor prefixed, as we can test for the standard property plus any vendor prefixes. A vendor prefix is a browser-specific CSS property prefix that required browser-specific implementations, such as the -webkit-prefix for certain WebKit-specific CSS properties.

For example, the following @supports rule will only apply the styles inside it if the browser supports the CSS transform property and requires a vendor prefix for it:

  .container {
    border: 4px solid red;
    color: red;
    padding: 10px;
  }
  @supports ((-webkit-transform: rotate(180deg)) or (transform: rotate(180deg))) {
    .container {
      border: 4px solid rgb(57, 57, 190);
      color: rgb(57, 57, 190);
    }
  }
  <div class="container">
    If the browser supports the CSS transform property 
    and requires a vendor prefix for it, 
    the border and text will be blue.
  </div>

This is particularly useful when used in conjunction with Autoprefixer, which can automatically add vendor prefixes to our CSS.

CSS features queries are supported in a lot of browsers.

Image Credits: Supported browser

Conclusion

  • Overall, CSS feature queries are a great way to improve the compatibility of our website with different browsers.
  • It allows us to check for features that are supported by the browser and then use different CSS rules depending on the results.
  • This can help us to avoid CSS issues that can occur when different browsers support different features.

Refer to this link to explore more on CSS feature queries.

Join Our Newsletter