Adopting graceful degradation in CSS

May 05, 2021css-practicescss

Previously on adopting progressive enhancement in CSS I talk about how we can apply progressive enhancement to provide fallbacks first to support old browsers. Opposite to progressive enhancement is graceful degradation.

Graceful degradation is a design philosophy that centers around trying to build a modern web site/application that will work in the newest browsers, but falls back to an experience that while not as good still delivers essential content and functionality in older browsers. - MDN

In CSS, graceful degradation can be applied to fallback strategy, starting out with mostly latest cutting-edge CSS features to develop the best possible websites, then adding fallbacks to support old/unknown browsers gracefully.

CSS degrade gracefully by design. CSS is forgivable, using an unknown CSS property might not break the whole site, but there is a good chance some parts won’t work as expected for some users.

A website design that is built to gracefully degrade is designed first with modern browsers in mind. That site is created to take advantage of the features of these modern web browsers.

You need to use CSS feature queries (@supports) to detect whether visiting browsers support a feature, and selectively apply different layouts depending on the result.

CSS feature queries let you specify declarations that depend on a browser’s support for one or more specific CSS features. The rule may be placed at the top level of your code or nested inside any other conditional group at-rule.

@supports (display: grid) {
  div {
    display: grid;
  }
}

If the browser doesn’t understand display: grid, then all of the styling inside the brackets will be applied. Otherwise all of that styling will be skipped.

/* using grid for modern browsers */

@supports not (display: grid) {
  /*
    default code for browsers don't support grid
    including overrides of the code above, if needed
  */
}

Well, not all browsers support feature queries. And the browsers that do not understand feature queries will skip all blocks of code inside. That’s probably bad. We can’t create a fallback by checking for browsers which do not have support feature queries using graceful degradation!

Progressive enhancement must be used to make sure fallbacks always run even when browsers won’t support feature queries or the feature you are testing for.

/* fallback code for older browsers */

@supports (display: grid) {
  /*
    code for newer browsers
    including overrides if needed
  */
}

Graceful degradation can be used more easily as a patch for an already existing product, it’s not perfect but requires less initial work.