A Complete Guide to CSS Cascade Layers

This is your complete guide to CSS 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. This guide is intended to help you fully understand what cascade layers are for, how and why you might choose to use them, the current levels of support, and the syntax of how you use them.

Table of Contents

Quick example

/* establish a layer order up-front, from lowest to highest priority */
@layer reset, defaults, patterns, components, utilities, overrides;

/* import stylesheets into a layer (dot syntax represents nesting) */
@import url('framework.css') layer(components.framework);

/* add styles to layers */
@layer utilities {
  /* high layer priority, despite low specificity */
  [data-color='brand'] { 
    color: var(--brand, rebeccapurple);
  }
}

@layer defaults {
  /* higher specificity, but lower layer priority */
  a:any-link { color: maroon; }
}

/* un-layered styles have the highest priority */
a {
  color: mediumvioletred;
}

Introduction: what are cascade layers?

CSS Cascade Layers are intended to solve tricky problems in CSS. Let’s take a look at the main problem and how cascade layers aim to solve it.

Problem: Specificity conflicts escalate

Many of us have been in situations where we want to override styles from elsewhere in our code (or a third-party tool), due to conflicting selectors. And over the years, authors have developed a number of “methodologies” and “best practices” to avoid these situations — such as “only using a single class” for all selectors. These rules are usually more about avoiding the cascade, rather than putting it to use.

Managing cascade conflicts and selector specificity has often been considered one of the harder — or at least more confusing — aspects of CSS. That may be partly because few other languages rely on a cascade as their central feature, but it’s also true that the original cascade relies heavily on heuristics (an educated-guess or assumption built into the code) rather than providing direct and explicit control to web authors.

Selector specificity, for example — our primary interaction with the cascade — is based on the assumption that more narrowly targeted styles (like IDs that are only used once) are likely more important than more generic and reusable styles (like classes and attributes). That is to say: how specific the selector is. That’s a good guess, but it’s not a totally reliable rule, and that causes some issues:

  • It combines the act of selecting elements, with the act of prioritizing rule-sets.
  • The simplest way to ‘fix’ a conflict with specificity is to escalate the problem by adding otherwise unnecessary selectors, or (gasp) throwing the !important hand-grenade.
.overly#powerful .framework.widget {
  color: maroon;
}

.my-single_class { /* add some IDs to this ??? */
  color: rebeccapurple; /* add !important ??? */
}

Solution: cascade layers provide control

Cascade layers give CSS authors more direct control over the cascade so we can build more intentionally cascading systems without relying as much on heuristic assumptions that are tied to selection.

Using the @layer at-rule and layered @imports, we can establish our own layers of the cascade — building from low-priority styles like resets and defaults, through themes, frameworks, and design systems, up to highest-priority styles, like components, utilities, and overrides. Specificity is still applied to conflicts within each layer, but conflicts between layers are always resolved by using the higher-priority layer styles.

@layer framework {
  .overly#powerful .framework.widget {
    color: maroon;
  }
}

@layer site {
  .my-single_class {
    color: rebeccapurple;
  }
}

These layers are ordered and grouped so that they don’t escalate in the same way that specificity and importance can. Cascade layers aren’t cumulative like selectors. Adding more layers doesn’t make something more important. They’re also not binary like importance — suddenly jumping to the top of a stack — or numbered like z-index, where we have to guess a big number (z-index: 9999999?). In fact, by default, layered styles are less important than un-layered styles.

@layer defaults {
  a:any-link { color: maroon; }
}

/* un-layered styles have the highest priority */
a {
  color: mediumvioletred;
}

Where do layers fit in the cascade?

The cascade is a series of steps (an algorithm) for resolving conflicts between styles.

html { --button: teal; }
button { background: rebeccapurple !important; }
.warning { background: maroon; }
<button class="warning" style="background: var(--button);">
  what color background?
</button>

With the addition of cascade layers, those steps are:

Illustration of the various specificity levels of the CSS cascade and where CSS Cascade Layers fit in it.

Selector specificity is only one small part of the cascade, but it’s also the step we interact with most, and is often used to refer more generally to overall cascade priority. People might say that the !important flag or the style attribute “adds specificity” — a quick way of expressing that the style becomes higher priority in the cascade. Since cascade layers have been added directly above specificity, it’s reasonable to think about them in a similar way: one step more powerful than ID selectors.

However, CSS Cascade Layers also make it more essential that we fully understand the role of !important in the cascade — not just as a tool for “increasing specificity” but as a system for balancing concerns.

!important origins, context, and layers are reversed!

As web authors, we often think of !important as a way of increasing specificity, to override inline styles or highly specific selectors. That works OK in most cases (if you’re OK with the escalation) but it leaves out the primary purpose of importance as a feature in the overall cascade.

Importance isn’t there to simply increase power — but to balance the power between various competing concerns.

Important origins

It all starts with origins, where a style comes from in the web ecosystem. There are three basic origins in CSS:

  • The browser (or user agent)
  • The user (often via browser preferences)
  • Web authors (that’s us!)

Browsers provide readable defaults for all the elements, and then users set their preferences, and then we (authors) provide the intended design for our web pages. So, by default, browsers have the lowest priority, user preferences override the browser defaults, and we’re able to override everyone.

But the creators of CSS were very clear that we should not actually have the final word:

If conflicts arise the user should have the last word, but one should also allow the author to attach style hints.

— Håkon Lie (emphasis added)

So importance provides a way for the browser and users to re-claim their priority when it matters most. When the !important flag is added to a style, three new layers are created — and the order is reversed!

  1. !important browser styles (most powerful)
  2. !important user preferences
  3. !important author styles
  4. normal author styles
  5. normal user preferences
  6. normal browser styles (least powerful)

For us, adding !important doesn’t change much — our important styles are pretty close to our normal styles — but for the browser and user it’s a very powerful tool for regaining control. Browser default style sheets include a number of important styles that it would be impossible for us to override, such as:

iframe:fullscreen {
  /* iframes in full-screen mode don't show a border. */
  border: none !important;
  padding: unset !important;
}

While most of the popular browsers have made it difficult to upload actual user stylesheets, they all offer user preferences: a graphic interface for establishing specific user styles. In that interface, there is always a checkbox available for users to choose if a site is allowed to override their preferences or not. This is the same as setting !important in a user stylesheet:

Screenshot of user font preferences.

Important context

The same basic logic is applied to context in the cascade. By default, styles from the host document (light DOM) override styles from an embedded context (shadow DOM). However, adding !important reverses the order:

  1. !important shadow context (most powerful)
  2. !important host context
  3. normal host context
  4. normal shadow context (least powerful)

Important styles that come from inside a shadow context override important styles defined by the host document. Here’s an odd-bird custom element with some styles written in the element template (shadow DOM), and some styles in the host page (light DOM) stylesheet:

Both color declarations have normal importance, and so the host page mediumvioletred takes priority. But the font-family declarations are flagged !important, giving advantage to the shadow-context, where fantasy is defined.

Important layers

Cascade layers work the same way as both origins and context, with the important layers in reverse-order. The only difference is that layers make that behavior much more noticeable.

Once we start using cascade layers, we will need to be much more cautious and intentional about how we use !important. It’s no longer a quick way to jump to the top of the priorities — but an integrated part of our cascade layering; a way for lower layers to insist that some of their styles are essential.

Since cascade layers are customizable, there’s no pre-defined order. But we can imagine starting with three layers:

  1. utilities (most powerful)
  2. components
  3. defaults (least powerful)

When styles in those layers are marked as important, they would generate three new, reversed important layers:

  1. !important defaults (most powerful)
  2. !important components
  3. !important utilities
  4. normal utilities
  5. normal components
  6. normal defaults (least powerful)

In this example, the color is defined by all three normal layers, and the utilities layer wins the conflict, applying the maroon color, as the utilities layer has a higher priority in @layers. But notice that the text-decoration property is marked !important in both the defaults and components layers, where important defaults take priority, applying the underline declared by defaults:

Establishing a layer order

We can create any number of layers and name them or group them in various ways. But the most important thing to do is to make sure our layers are applied in the right order of priority.

A single layer can be used multiple times throughout the codebase — cascade layers stack in the order they first appear. The first layer encountered sits at the bottom (least powerful), and the last layer at the top (most powerful). But then, above that, un-layered styles have the highest priority:

@layer layer-1 { a { color: red; } }
@layer layer-2 { a { color: orange; } }
@layer layer-3 { a { color: yellow; } }
/* un-layered */ a { color: green; }
  1. un-layered styles (most powerful)
  2. layer-3
  3. layer-2
  4. layer-1 (least powerful)

Then, as discussed above, any important styles are applied in a reverse order:

@layer layer-1 { a { color: red !important; } }
@layer layer-2 { a { color: orange !important; } }
@layer layer-3 { a { color: yellow !important; } }
/* un-layered */ a { color: green !important; }
  1. !important layer-1 (most powerful)
  2. !important layer-2
  3. !important layer-3
  4. !important un-layered styles
  5. normal un-layered styles
  6. normal layer-3
  7. normal layer-2
  8. normal layer-1 (least powerful)

Layers can also be grouped, allowing us to do more complicated sorting of top-level and nested layers:

@layer layer-1 { a { color: red; } }
@layer layer-2 { a { color: orange; } }
@layer layer-3 {
  @layer sub-layer-1 { a { color: yellow; } }
  @layer sub-layer-2 { a { color: green; } }
  /* un-nested */ a { color: blue; }
}
/* un-layered */ a { color: indigo; }
  1. un-layered styles (most powerful)
  2. layer-3
    1. layer-3 un-nested
    2. layer-3 sub-layer-2
    3. layer-3 sub-layer-1
  3. layer-2
  4. layer-1 (least powerful)

Grouped layers always stay together in the final layer order (for example, sub-layers of layer-3 will all be next to each other), but this otherwise behaves the same as if the list was “flattened” — turning this into a single six-item list. When reversing !important layer order, the entire list flattened is reversed.

But layers don’t have to be defined once in a single location. We give them names so that layers can be defined in one place (to establish layer order), and then we can append styles to them from anywhere:

/* describe the layer in one place */
@layer my-layer;

/* append styles to it from anywhere */
@layer my-layer { a { color: red; } }

We can even define a whole ordered list of layers in a single declaration:

@layer one, two, three, four, five, etc;

This makes it possible for the author of a site to have final say over the layer order. By providing a layer order up-front, before any third party code is imported, the order can be established and rearranged in one place without worrying about how layers are used in any third-party tool.

Syntax: Working with cascade layers

Let’s take a look at the syntax!

Order-setting @layer statements

Since layers are stacked in the order they are defined, it’s important that we have a tool for establishing that order all in one place!

We can use @layer statements to do that. The syntax is:

@layer <layer-name>#;

That hash (#) means we can add as many layer names as we want in a comma-separated list:

@layer reset, defaults, framework, components, utilities;

That will establish the layer order:

  1. un-layered styles (most powerful)
  2. utilities
  3. components
  4. framework
  5. defaults
  6. reset (least powerful)

We can do this as many times as we want, but remember: what matters is the order each name first appears. So this will have the same result:

@layer reset, defaults, framework;
@layer components, defaults, framework, reset, utilities;

The ordering logic will ignore the order of reset, defaults, and framework in the second @layer rule because those layers have already been established. This @layer list syntax doesn’t add any special magic to the layer ordering logic: layers are stacked based on the order in which the layers first appear in your code. In this case, reset appears first in the first @layer list. Any @layer statement that comes later can only append layer names to the list, but can’t move layers that already exist. This ensures that you can always control the final overall layer order from one location — at the very start of your styles.

These layer-ordering statements are allowed at the top of a stylesheet, before the @import rule (but not between imports). We highly recommend using this feature to establish all your layers up-front in a single place so you always know where to look or make changes.

Block @layer rules

The block version of the @layer rule only takes a single layer name, but then allows you to add styles to that layer:

@layer <layer-name> {
  /* styles added to the layer */
}

You can put most things inside an @layer block — media queries, selectors and styles, support queries, etc. The only things you can’t put inside a layer block are things like charset, imports, and namespaces. But don’t worry, there is a syntax for importing styles into a layer.

If the layer name hasn’t been established before, this layer rule will add it to the layer order. But if the name has been established, this allows you to add styles to existing layers from anywhere in the document — without changing the priority of each layer.

If we’ve established our layer-order up-front with the layer statement rule, we no longer need to worry about the order of these layer blocks:

/* establish the order up-front */
@layer defaults, components, utilities;

/* add styles to layers in any order */
@layer utilities {
  [hidden] { display: none; }
}

/* utilities will override defaults, based on established order */
@layer defaults {
  * { box-sizing: border-box; }
  img { display: block; }
}

Grouping (nested) layers

Layers can be grouped, by nesting layer rules:

@layer one {
  /* sorting the sub-layers */
  @layer two, three;

  /* styles ... */
  @layer three { /* styles ... */ }
  @layer two { /* styles ... */ }
}

This generates grouped layers that can be represented by joining the parent and child names with a period. That means the resulting sub-layers can also be accessed directly from outside the group:

/* sorting nested layers directly */
@layer one.two, one.three;

/* adding to nested layers directly */
@layer one.three { /* ... */ }
@layer one.two { /* ... */ }

The rules of layer-ordering apply at each level of nesting. Any styles that are not further nested are considered “un-layered” in that context, and have priority over further nested styles:

@layer defaults {
  /* un-layered defaults (higher priority) */
  :any-link { color: rebeccapurple; }

  /* layered defaults (lower priority) */
  @layer reset {
    a[href] { color: blue; }
  }
}

Grouped layers are also contained within their parent, so that the layer order does not intermix across groups. In this example, the top level layers are sorted first, and then the layers are sorted within each group:

@layer reset.type, default.type, reset.media, default.media;

Resulting in a layer order of:

  • un-layered (most powerful)
  • default group
    • default un-layered
    • default.media
  • default.type
  • reset group
    • reset un-layered
    • reset.media
    • reset.type

Note that layer names are also scoped so that they don’t interact or conflict with similarly-named layers outside their nested context. Both groups can have distinct media sub-layers.

This grouping becomes especially important when using @import or <link> to layer entire stylesheets. A third-party tool, like Bootstrap, could use layers internally — but we can nest those layers into a shared bootstrap layer-group on import, to avoid potential layer-naming conflicts.

Layering entire stylesheets with @import or <link>

Entire stylesheets can be added to a layer using the new layer() function syntax with @import rules:

/* styles imported into to the <layer-name> layer */
@import url('example.css') layer(<layer-name>);

There is also a proposal to add a layer attribute in the HTML <link> element — although this is still under development, and not yet supported anywhere. This can be used to import third-party tools or component libraries, while grouping any internal layers together under a single layer name — or as a way of organizing layers into distinct files.

Anonymous (un-named) layers

Layer names are helpful as they allow us to access the same layer from multiple places for sorting or combining layer blocks — but they are not required.

It’s possible to create anonymous (un-named) layers using the block layer rule:

@layer { /* ... */ }
@layer { /* ... */ }

Or using the import syntax, with a layer keyword in place of the layer() function:

/* styles imported into to a new anonymous layer */
@import url('../example.css') layer;

Each anonymous layer is unique, and added to the layer order where it is encountered. Anonymous layers can’t be referenced from other layer rules for sorting or appending more styles.

These should probably be used sparingly, but there might be a few use cases:

  • Projects could ensure that all styles for a given layer are required to be located in a single place.
  • Third-party tools could “hide” their internal layering inside anonymous layers so that they don’t become part of the tool’s public API.

Reverting values to the previous layer

There are several ways that we can use to “revert” a style in the cascade to a previous value, defined by a lower priority origin or layer. That includes a number of existing global CSS values, and a new revert-layer keyword that will also be global (works on any property).

Context: Existing global cascade keywords*

CSS has several global keywords which can be used on any property to help roll-back the cascade in various ways.

  • initial sets a property to the specified value before any styles (including browser defaults) are applied. This can be surprising as we often think of browser styles as the initial value — but, for example, the initial value of display is inline, no matter what element we use it on.
  • inherit sets the property to apply a value from its parent element. This is the default for inherited properties, but can still be used to remove a previous value.
  • unset acts as though simply removing all previous values — so that inherited properties once again inherit, while non-inherited properties return to their initial value.
  • revert only removes values that we’ve applied in the author origin (i.e. the site styles). This is what we want in most cases, since it allows the browser and user styles to remain intact.
New: the revert-layer keyword

Cascade layers add a new global revert-layer keyword. It works the same as revert, but only removes values that we’ve applied in the current cascade layer. We can use that to roll back the cascade, and use whatever value was defined in the previous layers.

In this example, the no-theme class removes any values set in the theme layer.

@layer default {
  a { color: maroon; }
}

@layer theme {
  a { color: var(--brand-primary, purple); }

  .no-theme {
    color: revert-layer;
  }
}

So a link tag with the .no-theme class will roll back to use the value set in the default layer. When revert-layer is used in un-layered styles, it behaves the same as revert — rolling back to the previous origin.

Reverting important layers

Things get interesting if we add !important to the revert-layer keyword. Because each layer has two distinct “normal” and “important” positions in the cascade, this doesn’t simply change the priority of the declaration — it changes what layers are reverted.

Let’s assume we have three layers defined, in a layer stack that looks like this:

  1. utilities (most powerful)
  2. components
  3. defaults (least powerful)

We can flesh that out to include not just normal and important positions of each layer, but also un-layered styles, and animations:

  1. !important defaults (most powerful)
  2. !important components
  3. !important utilities
  4. !important un-layered styles
  5. CSS animations
  6. normal un-layered styles
  7. normal utilities
  8. normal components
  9. normal defaults (least powerful)

Now, when we use revert-layer in a normal layer (let’s use utilities) the result is fairly direct. We revert only that layer, while everything else applies normally:

  1. !important defaults (most powerful)
  2. !important components
  3. !important utilities
  4. !important un-layered styles
  5. ✅ CSS animations
  6. ✅ normal un-layered styles
  7. ❌ normal utilities
  8. ✅ normal components
  9. ✅ normal defaults (least powerful)

But when we move that revert-layer into the important position, we revert both the normal and important versions along with everything in-between:

  1. !important defaults (most powerful)
  2. !important components
  3. !important utilities
  4. !important un-layered styles
  5. ❌ CSS animations
  6. ❌ normal un-layered styles
  7. ❌ normal utilities
  8. ✅ normal components
  9. ✅ normal defaults (least powerful)

Use cases: When would I want to use cascade layers?

So what sort of situations might we find ourselves using cascade layers? Here are several examples of when cascade layers make a lot of sense, as well as others where they do not make a lot sense.

Less intrusive resets and defaults

One of the clearest initial use cases would be to make low-priority defaults that are easy to override.

Some resets have been doing this already by applying the :when() pseudo-class around each selector. :when() removes all specificity from the selectors it is applied to, which has the basic impact desired, but also some downsides:

  • It has to be applied to each selector individually
  • Conflicts inside the reset have to be resolved without specificity

Layers allow us to more simply wrap the entire reset stylesheet, either using the block @layer rule:

/* reset.css */
@layer reset {
  /* all reset styles in here */
}

Or when you import the reset:

/* reset.css */
@import url(reset.css) layer(reset);

Or both! Layers can be nested without changing their priority. This way, you can use a third-party reset, and ensure it gets added to the layer you want whether or not the reset stylesheet itself is written using layers internally.

Since layered styles have a lower priority than default “un-layered” styles, this is a good way to start using cascade layers without re-writing your entire CSS codebase.

The reset selectors still have specificity information to help resolve internal conflicts, without wrapping each individual selector — but you also get the desired outcome of a reset stylesheet that is easy to override.

Managing a complex CSS architecture

As projects become larger and more complex, it can be useful to define clearer boundaries for naming and organizing CSS code. But the more CSS we have, the more potential we have for conflicts — especially from different parts of a system like a “theme” or a “component library” or a set of “utility classes.”

Not only do we want these organized by function, but it can also be useful to organize them based on what parts of the system take priority in the case of a conflict. Harry Robert’s Inverted Triangle CSS does a good job visualizing what those layers might contain.

In fact, the initial pitch for adding layers to the CSS cascade used the ITCSS methodology as a primary example, and a guide for developing the feature.

There is no particular technique required for this, but it’s likely helpful to restrict projects to a pre-defined set of top-level layers and then extend that set with nested layers as appropriate.

For example:

  1. low level reset and normalization styles
  2. element defaults, for basic typography and legibility
  3. themes, like light and dark modes
  4. re-usable patterns that might appear across multiple components
  5. layouts and larger page structures
  6. individual components
  7. overrides and utilities

We can create that top-level layer stack at the very start of our CSS, with a single layer statement:

@layer
  reset,
  default,
  themes,
  patterns,
  layouts,
  components,
  utilities;

The exact layers needed, and how you name those layers, might change from one project to the next.

From there, we create even more detailed layer breakdowns. Maybe our components themselves have defaults, structures, themes, and utilities internally.

@layer components {
  @layer defaults, structures, themes, utilities;
}

Without changing the top-level structure, we now have a way to further layer the styles within each component.

Using third-party tools and frameworks

Integrating third-party CSS with a project is one of the most common places to run into cascade issues. Whether we’re using a shared reset like Normalizer or CSS Remedy, a generic design system like Material Design, a framework like Bootstrap, or a utility toolkit like Tailwind — we can’t always control the selector specificity or importance of all the CSS being used on our sites. Sometimes, this even extends to internal libraries, design systems, and tools managed elsewhere in an organization.

As a result, we often have to structure our internal CSS around the third-party code, or escalate conflicts when they come up — with artificially high specificity or !important flags. And then we have to maintain those hacks over time, adapting to upstream changes.

Cascade layers give us a way to slot third-party code into the cascade of any project exactly where we want it to live — no matter how selectors are written internally. Depending on the type of library we’re using, we might do that in various ways. Let’s start with a basic layer-stack, working our way up from resets to utilities:

@layer reset, type, theme, components, utilities;

And then we can incorporate some tools…

Using a reset

If we’re using a tool like CSS Remedy, we might also have some reset styles of our own that we want to include. Let’s import CSS Remedy into a sub-layer of reset:

@import url('remedy.css') layer(reset.remedy);

Now we can add our own reset styles to the reset layer, without any further nesting (unless we want it). Since styles directly in reset will override any further nested styles, we can be sure our styles will always take priority over CSS Remedy if there’s a conflict — no matter what changes in a new release:

@import url('remedy.css') layer(reset.remedy);

@layer reset {
  :is(ol, ul)[role='list'] {
    list-style: none;
    padding-inline-start: 0;
  }
}

And since the reset layer is at the bottom of the stack, the rest of the CSS in our system will override both Remedy, and our own local reset additions.

Using utility classes

At the other end of our stack, “utility classes” in CSS can be a useful way to reproduce common patterns (like additional context for screen readers) in a broadly-applicable way. Utilities tend to break the specificity heuristic, since we want them defined broadly (resulting in a low specificity), but we also generally want them to “win” conflicts.

By having a utilities layer at the top of our layer stack, we can make that possible. We can use that in a similar way to the reset example, both loading external utilities into a sub-layer, and providing our own:

@import url('tailwind.css') layer(utilities.tailwind);

@layer utilities {
  /* from https://kittygiraudel.com/snippets/sr-only-class/ */
  /* but with !important removed from the properties */
  .sr-only {
    border: 0;
    clip: rect(1px, 1px, 1px, 1px);
    -webkit-clip-path: inset(50%);
    clip-path: inset(50%);
    height: 1px;
    overflow: hidden;
    margin: -1px;
    padding: 0;
    position: absolute;
    width: 1px;
    white-space: nowrap;
  }
}
Using design systems and component libraries

There are a lot of CSS tools that fall somewhere in the middle of our layer stack — combining typography defaults, themes, components, and other aspects of a system.

Depending on the particular tool, we might do something similar to the reset and utility examples above — but there are a few other options. A highly integrated tool might deserve a top-level layer:

@layer reset, bootstrap, utilities;
@import url('bootstrap.css') layer(bootstrap);

If these tools start to provide layers as part of their public API, we could also break it down into parts — allowing us to intersperse our code with the library:

@import url('bootstrap/reset.css') layer(reset.bootstrap);
@import url('bootstrap/theme.css') layer(theme.bootstrap);
@import url('bootstrap/components.css') layer(components.bootstrap);

@layer theme.local {
  /* styles here will override theme.bootstrap */
  /* but not interfere with styles from components.bootstrap */
}

Using layers with existing (un-layered, !important-filled) frameworks

As with any major language change, there’s going to be an adjustment period when CSS Cascade Layers become widely adopted. What happens if your team is ready to start using layers next month, but your favorite framework decides to wait another three years before they switch over to layered styles? Many frameworks will likely still use !important more often than we’d like! With !important layers reversed, that’s not ideal.

Still, layers can still help us solve the problem. We just have to get clever about it. We decide what layers we want for our project, and that means we can add layers above and also below the framework layers we create.

For now, though, we can use a lower layer to override !important styles from the framework, and a higher layer to override normal styles. Something like this:

@layer framework.important, framework.bootstrap, framework.local;
@import url('bootstrap.css') layer(framework.bootstrap);

@layer framework.local {
  /* most of our normal framework overrides can live here */
}

@layer framework.important {
  /* add !important styles in a lower layer */
  /* to override any !important framework styles */
}

It still feels like a bit of a hack, but it helps move us in the right direction — towards a more structured cascade. Hopefully it’s a temporary fix.

Designing a CSS tool or framework

For anyone maintaining a CSS library, cascade layers can help with internal organization, and even become part of the developer API. By naming internal layers of a library, we can allow users of our framework to hook into those layers when customizing or overriding our provided styles.

For example, Bootstrap could expose layers for their “reboot,” “grid,” and “utilities” — likely stacked in that order. Now a user can decide if they want to load those Bootstrap layers into different local layers:

@import url(bootstrap/reboot.css) layer(reset); /* reboot » reset.reboot */
@import url(bootstrap/grid.css) layer(layout); /* grid » layout.grid */
@import url(bootstrap/utils.css) layer(override); /* utils » override.utils */

Or the user might load them into a Bootstrap layer, with local layers interspersed:

@layer bs.reboot, bs.grid, bs.grid-overrides, bs.utils, bs.util-overrides;
@import url('bootstrap-all.css') layer(bs);

It’s also possible to hide internal layering from users, when desired, by grouping any private/internal layers inside an anonymous (un-named) layer. Anonymous layers will get added to the layer order where they are encountered, but will not be exposed to users re-arranging or appending styles.

I just want this one property to be more !important

Counter to some expectations, layers don’t make it easy to quickly escalate a particular style so that it overrides another.

If the majority of our styles are un-layered, then any new layer will be de-prioritized in relation to the default. We could do that to individual style blocks, but it would quickly become difficult to track.

Layers are intended to be more foundational, not style-by-style, but establishing consistent patterns across a project. Ideally, if we’ve set that up right, we get the correct result by moving our style to the appropriate (and pre-defined) layer.

If the majority of our styles already fall into well-defined layers, we can always consider adding a new highest-power layer at the top of a given stack, or using un-layered styles to override the layers. We might even consider having a debug layer at the top of the stack, for doing exploratory work outside of production.

But adding new layers on-the-fly can defeat the organizational utility of this feature, and should be used carefully. It’s best to ask: Why should this style override the other?

If the answer has to do with one type of style always overriding another type, layers are probably the right solution. That might be because we’re overriding styles that come from a place we don’t control, or because we’re writing a utility, and it should move into our utilities layer. If the answer has to do with more targeted styles overriding less targeted styles, we might consider making the selectors reflect that specificity.

Or, on rare occasions, we might even have styles that really are important — the feature simply doesn’t work if you override this particular style. We might say adding display: none to the [hidden] attribute belongs in our lowest-priority reset, but should still be hard to override. In that case, !important really is the right tool for the job:

@layer reset {
  [hidden] { display: none !important; }
}

Scoping and name-spacing styles? Nope!

Cascade layers are clearly an organizational tool, and one that ‘captures’ the impact of selectors, especially when they conflict. So it can be tempting at first glance to see them as a solution for managing scope or name-spacing.

A common first-instinct is to create a layer for each component in a project — hoping that will ensure (for example) that .post-title is only applied inside a .post.

But cascade conflicts are not the same as naming conflicts, and layers aren’t particularly well designed for this type of scoped organization. Cascade layers don’t constrain how selectors match or apply to the HTML, only how they cascade together. So unless we can be sure that component X always override component Y, individual component layers won’t help much. Instead, we’ll need to keep an eye on the proposed @scope spec that is being developed.

It can be useful to think of layers and component-scopes instead as overlapping concerns:

An illustration showing how CSS Cascade Layers can be organized by scope, such as buttons, cards, and login layers that fall into component, theme, and default scopes.

Scopes describe what we are styling, while layers describe why we are styling. We can also think of layers as representing where the style comes from, while scopes represent what the style will attach to.

Test your knowledge: Which style wins?

For each situation, assume this paragraph:

<p id="intro">Hello, World!</p>

Question 1

@layer ultra-high-priority {
  #intro {
    color: red;
  }
}

p {
  color: green;
}
What color is the paragraph?

Despite the layer having a name that sounds pretty important, un-layered styles have a higher priority in the cascade. So the paragraph will be green.

Question 2

@layer ren, stimpy;

@layer ren {
  p { color: red !important; }
}

p { color: green; }

@layer stimpy {
  p { color: blue !important; }
}
What color is the paragraph?

Our normal layer order is established at the start — ren at the bottom, then stimpy, then (as always) un-layered styles at the top. But these styles aren’t all normal, some of them are important. Right away, we can filter down to just the !important styles, and ignore the unimportant green. Remember that ‘origins and importance’ are the first step of the cascade, before we even take layering into account.

That leaves us with two important styles, both in layers. Since our important layers are reversed, ren moves to the top, and stimpy to the bottom. The paragraph will be red.

Question 3

@layer Montagues, Capulets, Verona;

@layer Montagues.Romeo { #intro { color: red; } }
@layer Montagues.Benvolio { p { color: orange; } }

@layer Capulets.Juliet { p { color: yellow; } }
@layer Verona { * { color: blue; } }
@layer Capulets.Tybalt { #intro { color: green; } }
What color is the paragraph?

All our styles are in the same origin and context, none are marked as important, and none of them are inline styles. We do have a broad range of selectors here, from a highly specific ID #intro to a zero specificity universal * selector. But layers are resolved before we take specificity into account, so we can ignore the selectors for now.

The primary layer order is established up front, and then sub-layers are added internally. But sub-layers are sorted along with their parent layer — meaning all the Montagues will have lowest priority, followed by all the Capulets, and then Verona has final say in the layer order. So we can immediately filter down to just the Verona styles, which take precedence. Even though the * selector has zero specificity, it will win.

Be careful about putting universal selectors in powerful layers!

Debugging layer conflicts in browser developer tools

Chrome, Safari, Firefox, and Edge browsers all have developer tools that allow you to inspect the styles being applied to a given element on the page. The styles panel of this element inspector will show applied selectors, sorted by their cascade priority (highest priority at the top), and then inherited styles below. Styles that are not being applied for any reason will generally be grayed out, or even crossed out — sometimes with additional information about why the style is not applied. This is the first place to look when debugging any aspect of the cascade, including layer conflicts.

Safari Technology Preview and Firefox Nightly already show (and sort) cascade layers in this panel. This tooling is expected to role out in the stable versions at the same time as cascade layers. The layer of each selector is listed directly above the selector itself:

Showing CSS Cascade Layers in Safari DevTools.
Safari
Showing CSS Cascade Layers in FireFox DevTools.
Firefox

Chrome/Edge are working on similar tools and expect to have them available in Canary (nightly) releases by the time cascade layers land in the stable release. We’ll make updates here as those tools change and improve.

Browser support and fallbacks

Cascade layers are (or will soon be) available by default in all the three major browser engines:

  • Chrome/Edge 99+
  • Firefox 97+
  • Safari (currently in the Technology Preview)

Since layers are intended as foundational building blocks of an entire CSS architecture, it is difficult to imagine building manual fallbacks in the same way you might for other CSS features. The fallbacks would likely involve duplicating large sections of code, with different selectors to manage cascade layering — or providing a much simpler fallback stylesheet.

Query feature support using @supports

There is a @supports feature in CSS that will allow authors to test for support of @layer and other at-rules:

@supports at-rule(@layer) {
  /* code applied for browsers with layer support */
}

@supports not at-rule(@layer) {
  /* fallback applied for browsers without layer support */
}

However, it’s also not clear when this query itself will be supported in browsers.

Assigning layers in HTML with the <link> tag

There is no official specification yet for a syntax to layer entire stylesheets from the html <link> tag, but there is a proposal being developed. That proposal includes a new layer attribute which can be used to assign the styles to a named or anonymous layer:

<!-- styles imported into to the <layer-name> layer -->
<link rel="stylesheet" href="example.css" layer="<layer-name>">

<!-- styles imported into to a new anonymous layer -->
<link rel="stylesheet" href="example.css" layer>

However, old browsers without support for the layer attribute will ignore it completely, and continue to load the stylesheet without any layering. The results could be pretty unexpected. So the proposal also extends the existing media attribute, so that it allows feature support queries in a support() function.

That would allow us to make layered links conditional, based on support for layering:

<link rel="stylesheet" layer="bootstrap" media="supports(at-rule(@layer))" href="bootstrap.css">

Potential polyfills and workarounds

The major browsers have all moved to an “evergreen” model with updates pushed to users on a fairly short release cycle. Even Safari regularly releases new features in “patch” updates between their more rare-seeming major versions.

That means we can expect browser support for these features to ramp up very quickly. For many of us, it may be reasonable to start using layers in only a few months, without much concern for old browsers.

For others, it may take longer to feel comfortable with the native browser support. There are many other ways to manage the cascade, using selectors, custom properties, and other tools. It’s also theoretically possible to mimic (or polyfill) the basic behavior. There are people working on that polyfill, but it’s not clear when that will be ready either.

More resources

CSS Cascade Layers is still evolving but there is already a lot of resources, including documentation, articles, videos, and demos to help you get even more familiar with layers and how they work.

Reference

Articles

Videos

Demos


A Complete Guide to CSS Cascade Layers originally published on CSS-Tricks. You should get the newsletter.

Very Extremely Practical CSS Art

I’ve always enjoyed the CSS art people create, but I’ve never ventured into it much myself. I’m familiar with many of the tricks involved, but still find it surprising every time: the way people are able to make such fluid and beautiful images out of little boxes. I always end up digging around in dev tools to see how things are done, but I had never seen the process unfold.

Any time CSS art starts getting attention, there is always someone around to say “that’s not practical” or “just use SVG” or something similarly dismissive and boring. It’s a terrible argument, even if it was true — no one is required to be Practical At All Times. What a terrible world that would be.

In October, I took the time to watch Lynn Fisher (Twitter, CodePen), one of my favorite CSS artists, live-stream her single-div process. Somewhere in the back of my mind, I assumed single-div artwork relied on highly complicated box-shadows—almost a pixel-art approach. I’m not sure where that idea came from, I probably saw someone do it years ago. But her process is much more “normal” and “practical” than I even realized: a number of reasonably layered, sized, and positioned background gradients.

Examples of Lynn Fischer's single div projects: repeated polar bears, plants on a shelf, a blinking light, and a tiny electronic piano.

Wait. I know how to do that. It’s not the technique that’s magical—it’s the audacity of turning a few gradients into a block of cheese with cake inside!

I’ve used all these properties before on client projects. I’ve created gradients, layered images, sized them, and positioned them for various effects. None of that is new, or complicated, or radical. I really didn’t learn anything at all about the CSS itself. But it had a huge impact on my perception of what I could accomplish with those simple tools. 

Within a few weeks, I was using that in production. Again, it’s nothing fancy or complicated—the perfect low-hanging fruit where a custom SVG feels just slightly too bulky. Here’s the effect I created, for a personal project, with a few custom properties to make adjustment easier:

Last week we used a similar trick as part of a Very Practical & Official client component library. It was Stacy Kvernmo’s idea, and it worked great.

Thanks Lynn, and all you other fabulous CSS Artists! Thanks for showing us all how much farther we can push this language that we love so much, and the Very Serious tools we use every day.


The post Very Extremely Practical CSS Art appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Embracing the Universal Web

There are constantly new features appearing in browsers—from subgrid to variable fonts to better developer tools. It's a really great time to be re-thinking everything we know about design on the web. Responsive design has served us well over the years, but it's still rooted in the limitations of the web from 2010. Ten years later, we're able to create more "Intrinsic" designs (a term coined by Jen Simmons) and hopefully, re-think some "best practices" that are now holding us back.

That's exciting but even more interesting to me in the context of a universal web. I began my career during the height of the Web Standards Project, CSS Zen Garden, Designing with Web Standards, and A Dao of Web Design—saturated in the philosophy of universally accessible design. CSS was relatively new, and explicitly designed to balance the desires of a web-creator (like me) with the needs of each individual user (also me), on any number of devices. Terms like "progressive enhancement" and "unobtrusive JavaScript" dominated the industry. We were moving away from "only works in X browser" warnings, to embrace an accessible and resilient user-centered medium.

Over the years, some of those concerns have become industry best-practice. CSS is now standard, and responsive design is the norm. But I also see (and build!) more and more apps targeted at a narrow range of modern, evergreen browsers. Or we ignore new features for years in order to support a browser like IE11. We've become resigned to a sense that browser support is binary, and we can only use the features that exactly match our "supported" browsers.

There are many reasons for that shift, including excitement around very cool new features. I don't think it's surprising for an industry to have these cycles, but I do think it's time to reflect on where we're heading. These new features are designed with universal accessibility in mind, and we also have new features for managing browser-support on a continuum, much like viewport-size.

Whatever we want to call it—Intrinsic Design, Resilient CSS, Progressive Enhancement, Universal Accessibility, or something else—I think we're poised for a new movement and a new era of web creation. It's time for us to take the lessons we learned from Responsive Web Design, adapting to screen sizes, and expand out: adapting to screen readers, legacy browsers, "smart" speakers, and any number of other interfaces.

I'm interested in new methodologies and conventions that move past managing specificity and cascade, or phones and laptops, to help us all manage accessibility and universal compatibility. I'm interested in finding ways to embrace all that is wonderful and new on the web, without abandoning the beautiful vision of a universal web. We have the tools. Let's do this.

The post Embracing the Universal Web appeared first on CSS-Tricks.

Introducing Sass Modules

Sass just launched a major new feature you might recognize from other languages: a module system. This is a big step forward for @import. one of the most-used Sass-features. While the current @import rule allows you to pull in third-party packages, and split your Sass into manageable "partials," it has a few limitations:

  • @import is also a CSS feature, and the differences can be confusing
  • If you @import the same file multiple times, it can slow down compilation, cause override conflicts, and generate duplicate output.
  • Everything is in the global namespace, including third-party packages – so my color() function might override your existing color() function, or vice versa.
  • When you use a function like color(). it’s impossible to know exactly where it was defined. Which @import does it come from?

Sass package authors (like me) have tried to work around the namespace issues by manually prefixing our variables and functions — but Sass modules are a much more powerful solution. In brief, @import is being replaced with more explicit @use and @forward rules. Over the next few years Sass @import will be deprecated, and then removed. You can still use CSS imports, but they won’t be compiled by Sass. Don’t worry, there’s a migration tool to help you upgrade!

Import files with @use

@use 'buttons';

The new @use is similar to @import. but has some notable differences:

  • The file is only imported once, no matter how many times you @use it in a project.
  • Variables, mixins, and functions (what Sass calls "members") that start with an underscore (_) or hyphen (-) are considered private, and not imported.
  • Members from the used file (buttons.scss in this case) are only made available locally, but not passed along to future imports.
  • Similarly, @extends will only apply up the chain; extending selectors in imported files, but not extending files that import this one.
  • All imported members are namespaced by default.

When we @use a file, Sass automatically generates a namespace based on the file name:

@use 'buttons'; // creates a `buttons` namespace
@use 'forms'; // creates a `forms` namespace

We now have access to members from both buttons.scss and forms.scss — but that access is not transferred between the imports: forms.scss still has no access to the variables defined in buttons.scss. Because the imported features are namespaced, we have to use a new period-divided syntax to access them:

// variables: <namespace>.$variable
$btn-color: buttons.$color;
$form-border: forms.$input-border;

// functions: <namespace>.function()
$btn-background: buttons.background();
$form-border: forms.border();

// mixins: @include <namespace>.mixin()
@include buttons.submit();
@include forms.input();

We can change or remove the default namespace by adding as <name> to the import:

@use 'buttons' as *; // the star removes any namespace
@use 'forms' as 'f';

$btn-color: $color; // buttons.$color without a namespace
$form-border: f.$input-border; // forms.$input-border with a custom namespace

Using as * adds a module to the root namespace, so no prefix is required, but those members are still locally scoped to the current document.

Import built-in Sass modules

Internal Sass features have also moved into the module system, so we have complete control over the global namespace. There are several built-in modules — math, color, string, list, map, selector, and meta — which have to be imported explicitly in a file before they are used:

@use 'sass:math';
$half: math.percentage(1/2);

Sass modules can also be imported to the global namespace:

@use 'sass:math' as *;
$half: percentage(1/2);

Internal functions that already had prefixed names, like map-get or str-index. can be used without duplicating that prefix:

@use 'sass:map';
@use 'sass:string';
$map-get: map.get(('key': 'value'), 'key');
$str-index: string.index('string', 'i');

You can find a full list of built-in modules, functions, and name changes in the Sass module specification.

New and changed core features

As a side benefit, this means that Sass can safely add new internal mixins and functions without causing name conflicts. The most exciting example in this release is a sass:meta mixin called load-css(). This works similar to @use but it only returns generated CSS output, and it can be used dynamically anywhere in our code:

@use 'sass:meta';
$theme-name: 'dark';

[data-theme='#{$theme-name}'] {
  @include meta.load-css($theme-name);
}

The first argument is a module URL (like @use) but it can be dynamically changed by variables, and even include interpolation, like theme-#{$name}. The second (optional) argument accepts a map of configuration values:

// Configure the $base-color variable in 'theme/dark' before loading
@include meta.load-css(
  'theme/dark', 
  $with: ('base-color': rebeccapurple)
);

The $with argument accepts configuration keys and values for any variable in the loaded module, if it is both:

  • A global variable that doesn’t start with _ or - (now used to signify privacy)
  • Marked as a !default value, to be configured
// theme/_dark.scss
$base-color: black !default; // available for configuration
$_private: true !default; // not available because private
$config: false; // not available because not marked as a !default

Note that the 'base-color' key will set the $base-color variable.

There are two more sass:meta functions that are new: module-variables() and module-functions(). Each returns a map of member names and values from an already-imported module. These accept a single argument matching the module namespace:

@use 'forms';

$form-vars: module-variables('forms');
// (
//   button-color: blue,
//   input-border: thin,
// )

$form-functions: module-functions('forms');
// (
//   background: get-function('background'),
//   border: get-function('border'),
// )

Several other sass:meta functions — global-variable-exists(), function-exists(), mixin-exists(), and get-function() — will get additional $module arguments, allowing us to inspect each namespace explicitly.

Adjusting and scaling colors

The sass:color module also has some interesting caveats, as we try to move away from some legacy issues. Many of the legacy shortcuts like lighten(). or adjust-hue() are deprecated for now in favor of explicit color.adjust() and color.scale() functions:

// previously lighten(red, 20%)
$light-red: color.adjust(red, $lightness: 20%);

// previously adjust-hue(red, 180deg)
$complement: color.adjust(red, $hue: 180deg);

Some of those old functions (like adjust-hue) are redundant and unnecessary. Others — like lighten. darken. saturate. and so on — need to be re-built with better internal logic. The original functions were based on adjust(). which uses linear math: adding 20% to the current lightness of red in our example above. In most cases, we actually want to scale() the lightness by a percentage, relative to the current value:

// 20% of the distance to white, rather than current-lightness + 20
$light-red: color.scale(red, $lightness: 20%);

Once fully deprecated and removed, these shortcut functions will eventually re-appear in sass:color with new behavior based on color.scale() rather than color.adjust(). This is happening in stages to avoid sudden backwards-breaking changes. In the meantime, I recommend manually checking your code to see where color.scale() might work better for you.

Configure imported libraries

Third-party or re-usable libraries will often come with default global configuration variables for you to override. We used to do that with variables before an import:

// _buttons.scss
$color: blue !default;

// old.scss
$color: red;
@import 'buttons';

Since used modules no longer have access to local variables, we need a new way to set those defaults. We can do that by adding a configuration map to @use:

@use 'buttons' with (
  $color: red,
  $style: 'flat',
);

This is similar to the $with argument in load-css(). but rather than using variable-names as keys, we use the variable itself, starting with $.

I love how explicit this makes configuration, but there’s one rule that has tripped me up several times: a module can only be configured once, the first time it is used. Import order has always been important for Sass, even with @import. but those issues always failed silently. Now we get an explicit error, which is both good and sometimes surprising. Make sure to @use and configure libraries first thing in any "entrypoint" file (the central document that imports all partials), so that those configurations compile before other @use of the libraries.

It’s (currently) impossible to "chain" configurations together while keeping them editable, but you can wrap a configured module along with extensions, and pass that along as a new module.

Pass along files with @forward

We don’t always need to use a file, and access its members. Sometimes we just want to pass it along to future imports. Let’s say we have multiple form-related partials, and we want to import all of them together as one namespace. We can do that with @forward:

// forms/_index.scss
@forward 'input';
@forward 'textarea';
@forward 'select';
@forward 'buttons';

Members of the forwarded files are not available in the current document and no namespace is created, but those variables, functions, and mixins will be available when another file wants to @use or @forward the entire collection. If the forwarded partials contain actual CSS, that will also be passed along without generating output until the package is used. At that point it will all be treated as a single module with a single namespace:

// styles.scss
@use 'forms'; // imports all of the forwarded members in the `forms` namespace

Note: if you ask Sass to import a directory, it will look for a file named index or _index)

By default, all public members will forward with a module. But we can be more selective by adding show or hide clauses, and naming specific members to include or exclude:

// forward only the 'input' border() mixin, and $border-color variable
@forward 'input' show border, $border-color;

// forward all 'buttons' members *except* the gradient() function
@forward 'buttons' hide gradient;

Note: when functions and mixins share a name, they are shown and hidden together.

In order to clarify source, or avoid naming conflicts between forwarded modules, we can use as to prefix members of a partial as we forward:

// forms/_index.scss
// @forward "<url>" as <prefix>-*;
// assume both modules include a background() mixin
@forward 'input' as input-*;
@forward 'buttons' as btn-*;

// style.scss
@use 'forms';
@include forms.input-background();
@include forms.btn-background();

And, if we need, we can always @use and @forward the same module by adding both rules:

@forward 'forms';
@use 'forms';

That’s particularly useful if you want to wrap a library with configuration or any additional tools, before passing it along to your other files. It can even help simplify import paths:

// _tools.scss
// only use the library once, with configuration
@use 'accoutrement/sass/tools' with (
  $font-path: '../fonts/',
);
// forward the configured library with this partial
@forward 'accoutrement/sass/tools';

// add any extensions here...


// _anywhere-else.scss
// import the wrapped-and-extended library, already configured
@use 'tools';

Both @use and @forward must be declared at the root of the document (not nested), and at the start of the file. Only @charset and simple variable definitions can appear before the import commands.

Moving to modules

In order to test the new syntax, I built a new open source Sass library (Cascading Color Systems) and a new website for my band — both still under construction. I wanted to understand modules as both a library and website author. Let’s start with the "end user" experience of writing site styles with the module syntax…

Maintaining and writing styles

Using modules on the website was a pleasure. The new syntax encourages a code architecture that I already use. All my global configuration and tool imports live in a single directory (I call it config), with an index file that forwards everything I need:

// config/_index.scss
@forward 'tools';
@forward 'fonts';
@forward 'scale';
@forward 'colors';

As I build out other aspects of the site, I can import those tools and configurations wherever I need them:

// layout/_banner.scss
@use '../config';

.page-title {
  @include config.font-family('header');
}

This even works with my existing Sass libraries, like Accoutrement and Herman, that still use the old @import syntax. Since the @import rule will not be replaced everywhere overnight, Sass has built in a transition period. Modules are available now, but @import will not be deprecated for another year or two — and only removed from the language a year after that. In the meantime, the two systems will work together in either direction:

  • If we @import a file that contains the new @use/@forward syntax, only the public members are imported, without namespace.
  • If we @use or @forward a file that contains legacy @import syntax, we get access to all the nested imports as a single namespace.

That means you can start using the new module syntax right away, without waiting for a new release of your favorite libraries: and I can take some time to update all my libraries!

Migration tool

Upgrading shouldn’t take long if we use the Migration Tool built by Jennifer Thakar. It can be installed with Node, Chocolatey, or Homebrew:

npm install -g sass-migrator
choco install sass-migrator
brew install sass/sass/migrator

This is not a single-use tool for migrating to modules. Now that Sass is back in active development (see below), the migration tool will also get regular updates to help migrate each new feature. It’s a good idea to install this globally, and keep it around for future use.

The migrator can be run from the command line, and will hopefully be added to third-party applications like CodeKit and Scout as well. Point it at a single Sass file, like style.scss. and tell it what migration(s) to apply. At this point there’s only one migration called module:

# sass-migrator <migration> <entrypoint.scss...>
sass-migrator module style.scss

By default, the migrator will only update a single file, but in most cases we’ll want to update the main file and all its dependencies: any partials that are imported, forwarded, or used. We can do that by mentioning each file individually, or by adding the --migrate-deps flag:

sass-migrator --migrate-deps module style.scss

For a test-run, we can add --dry-run --verbose (or -nv for short), and see the results without changing any files. There are a number of other options that we can use to customize the migration — even one specifically for helping library authors remove old manual namespaces — but I won’t cover all of them here. The migration tool is fully documented on the Sass website.

Updating published libraries

I ran into a few issues on the library side, specifically trying to make user-configurations available across multiple files, and working around the missing chained-configurations. The ordering errors can be difficult to debug, but the results are worth the effort, and I think we’ll see some additional patches coming soon. I still have to experiment with the migration tool on complex packages, and possibly write a follow-up post for library authors.

The important thing to know right now is that Sass has us covered during the transition period. Not only can imports and modules work together, but we can create "import-only" files to provide a better experience for legacy users still @importing our libraries. In most cases, this will be an alternative version of the main package file, and you’ll want them side-by-side: <name>.scss for module users, and <name>.import.scss for legacy users. Any time a user calls @import <name>, it will load the .import version of the file:

// load _forms.scss
@use 'forms';

// load _forms.input.scss
@import 'forms';

This is particularly useful for adding prefixes for non-module users:

// _forms.import.scss
// Forward the main module, while adding a prefix
@forward "forms" as forms-*;

Upgrading Sass

You may remember that Sass had a feature-freeze a few years back, to get various implementations (LibSass, Node Sass, Dart Sass) all caught up, and eventually retired the original Ruby implementation. That freeze ended last year, with several new features and active discussions and development on GitHub – but not much fanfare. If you missed those releases, you can get caught up on the Sass Blog:

Dart Sass is now the canonical implementation, and will generally be the first to implement new features. If you want the latest, I recommend making the switch. You can install Dart Sass with Node, Chocolatey, or Homebrew. It also works great with existing gulp-sass build steps.

Much like CSS (since CSS3), there is no longer a single unified version-number for new releases. All Sass implementations are working from the same specification, but each one has a unique release schedule and numbering, reflected with support information in the beautiful new documentation designed by Jina.

Sass Modules are available as of October 1st, 2019 in Dart Sass 1.23.0.

The post Introducing Sass Modules appeared first on CSS-Tricks.

CSS Custom Properties In The Cascade

CSS Custom Properties In The Cascade

CSS Custom Properties In The Cascade

Miriam Suzanne

Last month, I had a conversation on Twitter about the difference between “scoped” styles (generated in a build process) and “nested” styles native to CSS. I asked why, anecdotally, developers avoid the specificity of ID selectors, while embracing “scoped styles” generated by JavaScript? Keith Grant suggested that the difference lies in balancing the cascade* and inheritance, i.e. giving preference to proximity over specificity. Let’s take a look.

The Cascade

The CSS cascade is based on three factors:

  1. Importance defined by the !important flag, and style origin (user > author > browser)
  2. Specificity of the selectors used (inline > ID > class > element)
  3. Source Order of the code itself (latest takes precedence)

Proximity is not mentioned anywhere — the DOM-tree relationship between parts of a selector. The paragraphs below will both be red, even though #inner p describes a closer relationship than #outer p for the second paragraph:

See the Pen [Cascade: Specificity vs Proximity](https://codepen.io/smashingmag/pen/OexweJ/) by Miriam Suzanne.

See the Pen Cascade: Specificity vs Proximity by Miriam Suzanne.
<section id="outer">
  <p>This text is red</p>
  <div id="inner">
    <p>This text is also red!</p>
  </div>
</section>
#inner p {
  color: green;
}

#outer p {
  color: red;
}

Both selectors have the same specificity, they are both describing the same p element, and neither is flagged as !important — so the result is based on source-order alone.

BEM And Scoped Styles

Naming conventions like BEM (“Block__Element—Modifier”) are used to ensure that each paragraph is “scoped” to only one parent, avoiding the cascade entirely. Paragraph “elements” are given unique classes specific to their “block” context:

See the Pen [BEM Selectors & Proximity](https://codepen.io/smashingmag/pen/qzPyeM/) by Miriam Suzanne.

See the Pen BEM Selectors & Proximity by Miriam Suzanne.
<section class="outer">
  <p class="outer__p">This text is red</p>
  <div class="inner">
    <p class="inner__p">This text is green!</p>
  </div>
</section>
.inner__p {
  color: green;
}

.outer__p {
  color: red;
}

These selectors still have the same relative importance, specificity, and source order — but the results are different. “Scoped” or “modular” CSS tools automate that process, re-writing our CSS for us, based on the HTML. In the code below, each paragraph is scoped to its direct parent:

See the Pen [Scoped Style Proximity](https://codepen.io/smashingmag/pen/NZaLWN/) by Miriam Suzanne.

See the Pen Scoped Style Proximity by Miriam Suzanne.
<section outer-scope>
  <p outer-scope>This text is red</p>
  <div outer-scope inner-scope>
    <p inner-scope>This text is green!</p>
  </div>
</section>
p[inner-scope] {
  color: green
}

p[outer-scope] {
  color: red;
}

Inheritance

Proximity is not part of the cascade, but it is part of CSS. That’s where inheritance becomes important. If we drop the p from our selectors, each paragraph will inherit a color from its closest ancestor:

See the Pen [Inheritance: Specificity vs Proximity](https://codepen.io/smashingmag/pen/mZBGyN/) by Miriam Suzanne.

See the Pen Inheritance: Specificity vs Proximity by Miriam Suzanne.
#inner {
  color: green;
}

#outer {
  color: red;
}

Since #inner and #outer describe different elements, our div and section respectively, both color properties are applied without conflict. The nested p element has no color specified, so the results are determined by inheritance (the color of the direct parent) rather than cascade. Proximity takes precedence, and the #inner value overrides the #outer.

But there’s a problem: In order to use inheritance, we are styling everything inside our section and div. We want to target the paragraph color specifically.

(Re-)Introducing Custom Properties

Custom properties provide a new, browser-native solution; they inherit like any other property, but they don’t have to be used where they are defined. Using plain CSS, without any naming conventions or build tools, we can create a style that is both targeted and contextual, with proximity taking precedence over the cascade:

See the Pen [Custom Props: Specificity vs Proximity](https://codepen.io/smashingmag/pen/gNGdaO/) by Miriam Suzanne.

See the Pen Custom Props: Specificity vs Proximity by Miriam Suzanne.
p {
  color: var(--paragraph);
}

#inner {
  --paragraph: green;
}

#outer {
  --paragraph: red;
}

The custom --paragraph property inherits just like the color property, but now we have control over exactly how and where that value is applied. The --paragraph property acts similar to a parameter that can be passed into the p component, either through direct selection (specificity-rules) or context (proximity-rules).

I think this reveals a potential for custom properties that we often associate with functions, mixins, or components.

Custom “Functions” And Parameters

Functions, mixins, and components are all based on the same idea: reusable code, that can be run with various input parameters to get consistent-but-configurable results. The distinction is in what they do with the results. We’ll start with a striped-gradient variable, and then we can extend it into other forms:

html {
  --stripes: linear-gradient(
    to right,
    powderblue 20%, pink 20% 40%, white 40% 60%, pink 60% 80%, powderblue 80%
  );
}

That variable is defined on the root html element (could also use :root, but that adds unnecessary specificity), so our striped variable will be available everywhere in the document. We can apply it anywhere gradients are supported:

See the Pen [Custom Props: Variable](https://codepen.io/smashingmag/pen/NZwrrm/) by Miriam Suzanne.

See the Pen Custom Props: Variable by Miriam Suzanne.
body {
  background-image: var(--stripes);
}

Adding Parameters

Functions are used like variables, but define parameters for changing the output. We can update our --stripes variable to be more function-like by defining some parameter-like variables inside it. I’ll start by replacing to right with var(--stripes-angle), to create an angle-changing parameter:

html {
  --stripes: linear-gradient(
    var(--stripes-angle),
    powderblue 20%, pink 20% 40%, white 40% 60%, pink 60% 80%, powderblue 80%
  );
}

There are other parameters we could create, depending on what purpose the function is meant to serve. Should we allow users to pick their own stripe colors? If so, does our function accept 5 different color parameters or only 3 that will go outside-in like we have now? Do we want to create parameters for color-stops as well? Every parameter we add provides more customization at the cost of simplicity and consistency.

There is no universal right answer to that balance — some functions need to be more flexible, and others need to be more opinionated. Abstractions exist to provide consistency and readability in your code, so take a step back and ask what your goals are. What really needs to be customizable, and where should consistency be enforced? In some cases, it might be more helpful to have two opinionated functions, rather than one fully-customizable function.

To use the function above, we need to pass in a value for the --stripes-angle parameter, and apply the output to a CSS output property, like background-image:

/* in addition to the code above… */
html {
  --stripes-angle: 75deg;
  background-image: var(--stripes);
}

See the Pen [Custom Props: Function](https://codepen.io/smashingmag/pen/BgwOjj/) by Miriam Suzanne.

See the Pen Custom Props: Function by Miriam Suzanne.

Inherited Versus Universal

I defined the --stripes function on the html element out of habit. Custom properties inherit, and I want my function available everywhere, so it makes some sense to put it on the root element. That works well for inheriting variables like --brand-color: blue, so we might also expect it to work for our “function” as well. But if we try to use this function again on a nested selector, it won’t work:

See the Pen [Custom Props: Function Inheritance Fail](https://codepen.io/smashingmag/pen/RzjRrM/) by Miriam Suzanne.

See the Pen Custom Props: Function Inheritance Fail by Miriam Suzanne.
div {
  --stripes-angle: 90deg;
  background-image: var(--stripes);
}

The new --stripes-angle is ignored entirely. It turns out we can’t rely on inheritance for functions that need to be re-calculated. That’s because each property value is computed once per element (in our case, the html root element), and then the computed value is inherited. By defining our function at the document root, we don’t make the entire function available to descendants — only the computed result of our function.

That makes sense if you frame it in terms of the cascading --stripes-angle parameter. Like any inherited CSS property, it is available to descendants but not ancestors. The value we set on a nested div is not available to a function we defined on the html root ancestor. In order to create a universally-available function that will re-calculate on any element, we have to define it on every element:

See the Pen [Custom Props: Universal Function](https://codepen.io/smashingmag/pen/agLaNj/) by Miriam Suzanne.

See the Pen Custom Props: Universal Function by Miriam Suzanne.
* {
  --stripes: linear-gradient(
    var(--stripes-angle),
    powderblue 20%, pink 20% 40%, white 40% 60%, pink 60% 80%, powderblue 80%
  );
}

The universal selector makes our function available everywhere, but we can define it more narrowly if we want. The important thing is that it can only re-calculate where it is explicitly defined. Here are some alternatives:

/* make the function available to elements with a given selector */
.stripes { --stripes: /* etc… */; } 

/* make the function available to elements nested inside a given selector */
.stripes * { --stripes: /* etc… */; } 

/* make the function available to siblings following a given selector */
.stripes ~ * { --stripes: /* etc… */; } 

See the Pen [Custom Props: Scoped Function](https://codepen.io/smashingmag/pen/JQMvGM/) by Miriam Suzanne.

See the Pen Custom Props: Scoped Function by Miriam Suzanne.

This can be extended with any selector logic that doesn’t rely on inheritance.

Free Parameters And Fallback Values

In our example above, var(--stripes-angle) has no value and no fallback. Unlike Sass or JS variables that must be defined or instantiated before they are called, CSS custom properties can be called without ever being defined. This creates a “free” variable, similar to a function parameter that can be inherited from the context.

We can eventually define the variable on html or :root (or any other ancestor) to set an inherited value, but first we need to consider the fallback if no value is defined. There are several options, depending on exactly what behavior we want

  1. For “required” parameters, we don’t want a fallback. As-is, the function will do nothing until --stripes-angle is defined.
  2. For “optional” parameters, we can provide a fallback value in the var() function. After the variable-name, we add a comma, followed by the default value:
var(--stripes-angle, 90deg)

Each var() function can only have one fallback — so any additional commas will be part of that value. That makes it possible to provide complex defaults with internal commas:

html {
  /* Computed: Hevetica, Ariel, sans-serif */
  font-family: var(--sans-family, Hevetica, Ariel, sans-serif);

  /* Computed: 0 -1px 0 white, 0 1px 0 black */
  test-shadow: var(--shadow, 0 -1px 0 white, 0 1px 0 black);
} 

We can also use nested variables to create our own cascade rules, giving different priorities to the different values:

var(--stripes-angle, var(--global-default-angle, 90deg))
  1. First, try our explicit parameter (--stripes-angle);
  2. Fallback to a global “user default” (--user-default-angle) if it’s available;
  3. Finally, fallback to our “factory default” (90deg).

See the Pen [Custom Props: Fallback Values](https://codepen.io/smashingmag/pen/jjGvVm/) by Miriam Suzanne.

See the Pen Custom Props: Fallback Values by Miriam Suzanne.

By setting fallback values in var() rather than defining the custom property explicitly, we ensure that there are no specificity or cascade restrictions on the parameter. All the *-angle parameters are “free” to be inherited from any context.

Browser Fallbacks Versus Variable Fallbacks

When we’re using variables, there are two fallback paths we need to keep in mind:

  1. What value should be used by browsers without variable support?
  2. What value should be used by browsers that support variables, when a particular variable is missing or invalid?
p {
  color: blue;
  color: var(--paragraph);
}

While old browsers will ignore the variable declaration property, and fallback to blue — modern browsers will read both and use the latter. Our var(--paragraph) might not be defined, but it is valid and will override the previous property, so browsers with variable support will fallback to the inherited or initial value, as if using the unset keyword.

That may seem confusing at first, but there are good reasons for it. The first is technical: browser engines handle invalid or unknown syntax at “parse time” (which happens first), but variables are not resolved until “computed-value time” (which happens later).

  1. At parse time, declarations with invalid syntax are ignored completely — falling back on earlier declarations. This is the path that old browsers will follow. Modern browsers support the variable syntax, so the previous declaration is discarded instead.
  2. At computed-value time the variable is compiled as invalid, but it’s too late — the previous declaration was already discarded. According to the spec, invalid variable values are treated the same as unset:

See the Pen [Custom Props: Invalid/Unsupported vs Undefined](https://codepen.io/smashingmag/pen/VJMGbJ/) by Miriam Suzanne.

See the Pen Custom Props: Invalid/Unsupported vs Undefined by Miriam Suzanne.
html {
  color: red;
  
  /* ignored as *invalid syntax* by all browsers */
  /* - old browsers: red */
  /* - new browsers: red */
  color: not a valid color; 
  color: var(not a valid variable name); 
  
  /* ignored as *invalid syntax* by browsers without var support */
  /* valid syntax, but invalid *values* in modern browsers */
  /* - old browsers: red */
  /* - new browsers: unset (black) */
  --invalid-value: not a valid color value;
  color: var(--undefined-variable);
  color: var(--invalid-value);
}

This is also good for us as authors, because it allows us to play with more complex fallbacks for the browsers that support variables, and provide simple fallbacks for older browsers. Even better, that allows us to use the null/undefined state to set required parameters. This becomes especially important if we want to turn a function into a mixin or component.

Custom Property “Mixins”

In Sass, the functions return raw values, while mixins generally return actual CSS output with property-value pairs. When we define a universal --stripes property, without applying it to any visual output, the result is function-like. We can make that behave more like a mixin, by defining the output universally as well:

* {
  --stripes: linear-gradient(
    var(--stripes-angle),
    powderblue 20%, pink 20% 40%, white 40% 60%, pink 60% 80%, powderblue 80%
  );
  background-image: var(--stripes);
}

As long as --stripes-angle remains invalid or undefined, the mixin fails to compile, and no background-image will be applied. If we set a valid angle on any element, the function will compute and give us a background:

div {
  --stripes-angle: 30deg; /* generates the background */
}

Unfortunately, that parameter-value will inherit, so the current definition creates a background on the div and all descendants. To fix that, we have to make sure the --stripes-angle value doesn’t inherit, by resting it to initial (or any invalid value) on every element. We can do that on the same universal selector:

See the Pen [Custom Props: Mixin](https://codepen.io/smashingmag/pen/ZdXMJx/) by Miriam Suzanne.

See the Pen Custom Props: Mixin by Miriam Suzanne.
* {
  --stripes-angle: initial;
  --stripes: /* etc… */;
  background-image: var(--stripes);
}

Safe Inline Styles

In some cases, we need the parameter to be set dynamically from outside CSS — based on data from a back-end server or front-end framework. With custom properties, we can safely define variables in our HTML without worrying about the usual specificity issues:

See the Pen [Custom Props: Mixin + Inline Style](https://codepen.io/smashingmag/pen/qzPMPv/) by Miriam Suzanne.

See the Pen Custom Props: Mixin + Inline Style by Miriam Suzanne.
<div style="--stripes-angle: 30deg">...</div>

Inline styles have a high specificity, and are very hard to override — but with custom properties, we we have another option: ignore it. If we set the div to background-image: none (for example) that inline variable will have no impact. To take it even farther, we can create an intermediate variable:

* { --stripes-angle: var(--stripes-angle-dynamic, initial); }

Now we have the option to define --stripes-angle-dynamic in the HTML, or ignore it, and set --stripes-angle directly in our stylesheet.

See the Pen [Custom Props: Mixin + Inline / Override](https://codepen.io/smashingmag/pen/ZdXMao/) by Miriam Suzanne.

See the Pen Custom Props: Mixin + Inline / Override by Miriam Suzanne.

Preset Values

For more complex values, or common patterns we want to re-use, we can also provide a few preset variables to choose from:

* {
  --tilt-down: 6deg;
  --tilt-up: -6deg;
}

And use those presets, rather than setting the value directly:

<div style="--stripes-angle: var(--tilt-down)">...</div>

See the Pen [Custom Props: Mixin + Presets](https://codepen.io/smashingmag/pen/LKemZm/) by Miriam Suzanne.

See the Pen Custom Props: Mixin + Presets by Miriam Suzanne.

This is great for creating charts and graphs based on dynamic data, or even laying out a day planner.

See the Pen [Bar chart in CSS grid + variables](https://codepen.io/smashingmag/pen/wLrEyg/) by Miriam Suzanne.

See the Pen Bar chart in CSS grid + variables by Miriam Suzanne.

Contextual Components

We can also re-frame our “mixin” as a “component” by applying it to an explicit selector, and making the parameters optional. Rather than relying on the presence-or-absence of --stripes-angle to toggle our output, we can rely on the presence-or-absence of a component selector. That allows us to set fallback values safely:

See the Pen [Custom Props: Component](https://codepen.io/smashingmag/pen/QXqVmM/) by Miriam Suzanne.

See the Pen Custom Props: Component by Miriam Suzanne.
[data-stripes] {
  --stripes: linear-gradient(
    var(--stripes-angle, to right),
    powderblue 20%, pink 20% 40%, white 40% 60%, pink 60% 80%, powderblue 80%
  );
  background-image: var(--stripes);
}

By putting the fallback inside the var() function, we can leave --stripes-angle undefined and “free” to inherit a value from outside the component. This is a great way to expose certain aspects of a component style to contextual input. Even “scoped” styles generated by a JS framework (or scoped inside the shadow-DOM, like SVG icons) can use this approach to expose specific parameters for outside influence.

Isolated Components

If we don’t want to expose the parameter for inheritance, we can define the variable with a default value:

[data-stripes] {
  --stripes-angle: to right;
  --stripes: linear-gradient(
    var(--stripes-angle, to right),
    powderblue 20%, pink 20% 40%, white 40% 60%, pink 60% 80%, powderblue 80%
  );
  background-image: var(--stripes);
}

These components would also work with a class, or any other valid selector, but I chose the data-attribute to create a namespace for any modifiers we want:

[data-stripes='vertical'] { --stripes-angle: to bottom; }
[data-stripes='horizontal'] { --stripes-angle: to right; }
[data-stripes='corners'] { --stripes-angle: to bottom right; }

See the Pen [Custom Props: Isolated Components](https://codepen.io/smashingmag/pen/agLaGX/) by Miriam Suzanne.

See the Pen Custom Props: Isolated Components by Miriam Suzanne.

Selectors and Parameters

I often wish I could use data-attributes to set a variable — a feature supported by the CSS3 attr() specification, but not yet implemented in any browsers (see the resources tab for linked issues on each browser). That would allow us to more closely associate a selector with a particular parameter:

<div data-stripes="30deg">...</div>


/* Part of the CSS3 spec, but not yet supported */
/* attr( , ) */
[data-stripes] {
  --stripes-angle: attr(data-stripes angle, to right);
}

In the meantime, we can achieve something similar by using the style attribute:

See the Pen [Custom Props: Style Selectors](https://codepen.io/smashingmag/pen/PrJdBG/) by Miriam Suzanne.

See the Pen Custom Props: Style Selectors by Miriam Suzanne.
<div style="--stripes-angle: 30deg">...</div>


/* The `*=` atttribute selector will match a string anywhere in the attribute */
[style*='--stripes-angle'] {
  /* Only define the function where we want to call it */
  --stripes: linear-gradient(…);  
}

This approach is most useful when we want to include other properties in addition to the parameter being set. For example, setting a grid area could also add padding and background:

[style*='--grid-area'] {
  background-color: white;
  grid-area: var(--grid-area, auto / 1 / auto / -1);
  padding: 1em;
}

Conclusion

When we start to put all these pieces together, it becomes clear that custom properties go far beyond the common variable use-cases we’re familiar with. We’re not only able to store values, and scope them to the cascade — but we can use them to manipulate the cascade in new ways, and create smarter components directly in CSS.

This calls for us to re-think many of the tools we’ve relied on in the past — from naming conventions like SMACSS and BEM, to “scoped” styles and CSS-in-JS. Many of those tools help work around specificity, or manage dynamic styles in another language — use-cases that we can now address directly with custom properties. Dynamic styles that we’ve often calculated in JS, can now be handled by passing raw data into the CSS.

At first, these changes may be seen as “added complexity” — since we’re not used to seeing logic inside CSS. And, as with all code, over-engineering can be a real danger. But I’d argue that in many cases, we can use this power not to add complexity, but to move complexity out of third-party tools and conventions, back into the core language of web design, and (more importantly) back into the browser. If our styles require calculation, that calculation ought to live inside our CSS.

All of these ideas can be taken much further. Custom properties are just starting to see wider adoption, and we’ve only begun to scratch the surface of what’s possible. I’m excited to see where this goes, and what else people come up with. Have fun!

Further Reading

Smashing Editorial (dm, il)