What are 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;}}`;
document.head.appendChild(style);
// check if the variable is set
const hasSupport = getComputedStyle(document.documentElement)
.getPropertyValue(varName)
.includes('true');
// remove the style element
document.head.removeChild(style);
// (optionally) add a root class
const supportClass = hasSupport ? 'layers' : 'no-layers';
document.documentElement.classList.add(supportClass);
if (hasSupport) {
// load the plain (unpolyfilled) stylesheet
const styles = document.createElement('link');
styles.rel = 'stylesheet';
styles.href = './dist/styles.css';
document.head.appendChild(styles);
} else {
// load the polyfilled stylesheet
const polyfilled = document.createElement('link');
polyfilled.rel = 'stylesheet';
polyfilled.href = './dist/polyfilled.css';
document.head.appendChild(polyfilled);
}
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.