Whats a Basic Use Case for Cascade Layers in CSS? Chris Coyier

Publish date: 2024-05-16

April 10, 2023

Say you pull in Bootstrap (or any other grab-and-go CSS library) something like:

@import url("https://cdn.com/bootstrap.min.css")Code language: CSS (css)

Now you use it to style a card or something…

<div class="card"> <div class="card-body"> <h5 class="card-title">Card title</h5> ...Code language: HTML, XML (xml)

But you don’t like the amount of margin on .card-title. Now what? Options:

 .card-title { margin: var(--my-margin-override); }Code language: CSS (css)
 .card-title { margin: var(--my-margin-override) !important; }Code language: CSS (css)
 h5.card-title { margin: var(--my-margin-override); } .card-title.card-title { margin: var(--my-margin-override); }Code language: CSS (css)

I’m not a big fan of any of those approaches. They all come with at best little mental overhead and at worst a gnarly styling battle.

This is an extremely not rare situation.

Cascade Layers offers a delightfully simple fix: make your library CSS less powerful:

@import url("https://cdn.com/bootstrap.min.css") layer(framework);Code language: CSS (css)

Now any other CSS (that is either “unlayered” or is intentionally put into a “higher” layer) will automatically win over Bootstrap. I can just do:

 h5 { margin: 2rem; }Code language: CSS (css)

How this effects how authors write CSS over time remains to be seen, in my eyes. But conversations like “always keep specificity low” which has long been a sensible over-arching CSS philosophy will change with Cascade Layers in play. Specificity just matters less when the tools to ensure the styles you want to apply more are easy to configure up front.

🤘

ncG1vNJzZmibmKe2tK%2FOsqCeql6jsrV7kWlpbGdgaXxyfI6wn5qso2Kubq7ArKCcZaWosm6vwKycZp6fp3qkrdKcmJ2dXaGuurHRrGSipl2YwLR7