Skip to content

Instantly share code, notes, and snippets.

@xiaochengh
Last active December 8, 2021 00:35
Show Gist options
  • Save xiaochengh/58c793e3bf06a1bb0f7d472ebb170feb to your computer and use it in GitHub Desktop.
Save xiaochengh/58c793e3bf06a1bb0f7d472ebb170feb to your computer and use it in GitHub Desktop.
CSS cascade layer explainer

Use case: Set base style with a 3rd party library, and then override some style.

With cascade layers (spec), this can be done by simply putting 3rd party rules and author's own rules in different layers, so that author's own rules have higher priority than the 3rd party library.

There is no need to tweak selector specificity or source ordering.

3rd party style library:

.animated { animation-name: plain-animation; }
@keyframes plain-animation { ... }
... /* Other style rules */

Author's HTML:

<style>
/* Define layer ordering */
@layer plain, fancy;

/* Import 3rd party style into the 'plain' layer; See also note below */
@import url(3rd-party-style.css) layer(plain);
</style>
<link rel="stylesheet" href="author-style.css">

<div class="animated"></div>

...

author-style.css:

/* Author's own style rules in the 'fancy' layer to override the animation */
@layer fancy {
  .animated { animation-name: fancy-animation; }
  @keyframes fancy-animation { ... }
}

/* Now .animated is animated with fancy-animation */

Note: When importing an external stylesheet into a layer, it's recommended to inline the @import rule in a <style> element, so that preload scanners can pick it up to prevent forming a chain of sequential requests of external stylesheets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment