What’s a Basic Use Case for Cascade Layers in CSS?

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:

/* Same specificity might work, 
   as long as you're always loading you
   are always loading your CSS after */
.card-title {
  margin: var(--my-margin-override);
}Code language: CSS (css)
/* The: I JUST WANNA WIN!!!! method */
.card-title {
  margin: var(--my-margin-override) !important;
}Code language: CSS (css)
/* More tempered approaches to specificity battles */
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:

/* This unlayered style will win 
   over Bootstraps .card-title by 
   virtue of Cascade Layers */
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.


CodePen

I work on CodePen! I'd highly suggest you have a PRO account on CodePen, as it buys you private Pens, media uploads, realtime collaboration, and more.

Get CodePen Pro

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top ⬆️