CSS Cascade Layers Polyfill Demo

What are Cascade Layers?

...a CSS feature that allows us to define explicit contained layers of specificity, so that we have full control over which styles take priority in a project without relying on specificity hacks or !important.
Miriam Suzanne, A Complete Guide to CSS Cascade Layers

What does the Cascade Layers Polyfill do?

It uses PostCSS to pre-process the CSS, meaning you can write CSS with Cascade Layers and not worry about it only being available in some of the latest browsers. The polyfill is available as an NPM package and you can learn more about it by reading Cascade Layers – There’s a Polyfill for That! by Sana Javed on the OddBird blog.

How to use the Cascade Layers Polyfill

Assuming you have two CSS files, one main stylesheet using Layers and another preprocessed with the polyfill, you can test for @layer support and conditionally use the appropriate stylesheet:

/* inspired by: https://codepen.io/miriamsuzanne/pen/poLOYrz */

const varName = '--js-test-layer-support';

// inject a style element with a layered variable
const style = document.createElement('style');
style.textContent = `@layer {:root{${varName}: true;}}`;

// check if the variable is set
const hasSupport = getComputedStyle(document.documentElement)

// remove the style element

// (optionally) add a root class
const supportClass = hasSupport ? 'layers' : 'no-layers';

if (hasSupport) {
  // load the plain (unpolyfilled) stylesheet
  const styles = document.createElement('link');
  styles.rel = 'stylesheet';
  styles.href = './dist/styles.css';
} else {
  // load the polyfilled stylesheet
  const polyfilled = document.createElement('link');
  polyfilled.rel = 'stylesheet';
  polyfilled.href = './dist/polyfilled.css';
Select a stylesheet below!

The polyfilled CSS was transformed by the PostCSS plugin, and the unpolyfilled CSS is unchanged.

Sample Content for Layers and the Polyfill

When layers are supported or if the polyfill is in use, you will see the default bootstrap button styles. In this demo, the Bootstrap CSS is imported into the lowest priority layer making any CSS written outside of the "framework" layer take priority. This means you can apply your own styles without having to worry about increased specificity.