Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Cascade Layers, a Proposal

A syntax proposal for Cascade Layers #4470. This does not include full discussion of the Cascade Layer purpose and use-cases, which can be found in the various linked issues, but attempts to answer many of the outstanding questions about how we might implement a layering feature.

Collaborators:

  • Elika Etemad
  • Florian Rivoal
  • Miriam Suzanne
  • Tab Atkins Jr.

Where do Cascade Layers fit in the cascade? #5003

  1. Origins & Importance
  2. Context (eg Shadow DOM)
  3. Layers
  4. Specificity
  5. Source Order

This avoids a lot of implementation complexity, while still giving authors a way to group and layer selectors. In some ways this is similar to adding a new top-level "specificity", but the interaction with !important is a bit different.

How do Cascade Layers interact with Shadow DOM? #4984

Shadow DOM can be addressed in the cascade before layers are taken into account. We don't expect any particular issues with this interaction.

How do Cascade Layers interact with !important? #4971

With Cascade Layers at a lower level than origins & importance, layered declarations will continue to divide into the existing origin structure and author layers:

  1. Transitions
  2. ❗️User Agent
  3. ❗️User
  4. ❗️Author
  5. Animations
  6. Author
  7. User
  8. User Agent

Within the two author origins, !important declarations will follow origin-ordering logic: with !important layers reversed in order. Unlayered styles rank highest in the normal origin, and lowest in the !important origin.

  1. ❗️Author
    1. ❗️Reset
    2. ❗️Base
    3. ❗️Patterns
    4. ❗️Components
    5. ❗️unlayered
  2. Animations
  3. Author
    1. unlayered
    2. Components
    3. Patterns
    4. Base
    5. Reset

Layers provide the selector-override use-case that leads authors to misuse !important. By making layers work the same as origins in this way, we are building on the original intent of the flag, and helping teach proper usage. Since authors are in control of the layering order, it should still be possible to generate any overrides necessary.

Style Attribute?

A final question is where does the style attribute fit in all this. In level 2 it was described through specificity and belonged to the normal author layer. In level 3, it is described through the scoping mechanism, but that's not implemented anywhere, so maybe it's time to re-explain it some other way. In order to remain backwards compatible, it needs to stay at the top of both Author origins:

  1. ❗️Author
    1. ❗️Style Attribute
    2. ❗️Defined Layers...
    3. ❗️unlayered
  2. Animations
  3. Author
    1. Style Attribute
    2. unlayered
    3. Defined Layers...

This can be described as a top Cascade Layer that is not reversed in the !important origin, or as an additional independent stage in the cascade, between Context and Layers.

What are the proper "levels" for managing Cascade Layers? #4969

Much like media-queries, Cascade Layers can be managed using both a combination of file-import & at-rule syntax.

Block Syntax:

/* @layer <name>? { <contents> } */
@layer reset {
  *, ::before, ::after { box-sizing: border-box; }
  html { line-sizing: normal; }
  body { margin: 0; }
}

@layer base {
  /* site base styles */
}

@layer components {
  /* site components styles */
}

@layer reset {
  /* add to the reset layer from elsewhere */
}

Layers are stacked in order of their first appearance - with later-appearing layers stacked above (and overriding) previously defined layers. That builds on existing cascade rules and organizational best-practice, while also making it possible to use layers without any explicit stacking syntax.

Ordering layers:

If authors do want to re-order layers, they can do that already by listing empty layer blocks before any other layers:

@layer reset {}
@layer base {}
@layer bootstrap {}
@layer components {}

Still, it might be nice for authors to have an explicit shorthand to achieve the same outcome. We could add a @layers rule that has exactly the same functionality:

@layers reset, base, bootstrap, components;

This would also help resolve the fact that @import rules are required before all other CSS blocks. By allowing @layers to appear before/between @import rules, we can avoid any weird syntactic issues with allowing @layer in that position only when empty.

Import Syntax:

The exact syntax here still needs some debate. The most direct approach would be allowing a url() in place of a {…} code block:

/* @layer <name>? url(<contents>) */
@layer reset url(reset.css);
@layer bootstrap url(bootstrap.css);

Other proposals include building on @import, creating a new at-rule, or allowing imports to be nested inside the block syntax:

@import layer reset url(reset.css);

@layer-import reset url(reset.css);

@layer reset { 
  @import url(reset.css); 
}

/* etc… */

In any case, this raises some question around ordering of @layer and @import rules -- which are currently required to come first. We may also want a syntax for HTML <link> imports?

"Nested" Layers:

Providing both block & file-level syntax means block-layers from a file can be grouped and "nested" inside a named import-layer:

/* bootstrap.css */
@layer reset {}
@layer base {}
@layer components {}
/* …potentially also some unlayered code… */

/* site.css */
@layer bootstrap url(bootstrap.css);

This would generate a bootstrap layer with reset, base, components, and unlayered sub-layers:

  1. Author
    1. unlayered
    2. Bootstrap
      1. unlayered
      2. Components
      3. Base
      4. Reset

That can be useful as a naming and organizing convention for authors, but the reality can be flattened without any change to the behavior:

  1. Author
    1. unlayered
    2. Bootstrap unlayered
    3. Bootstrap Components
    4. Bootstrap Base
    5. Bootstrap Reset

Using a well-designed library, and a syntax for nested-naming, authors could integrate their code with the existing library layers:

/* re-ordering "nested" layers: */
@layer bootstrap reset {};
@layer bootstrap base {};
@layer base {};
@layer bootstrap components {};
@layer components {};

/* importing & naming the bootstrap layers: */
@layer bootstrap url(bootstrap.css);

@layer bootstrap base {
  /* add code at the bootstrap-base layer… */
}

This "nesting" could also use a dot notation, commas, or some other syntax:

/* re-ordering "nested" layers: */
@layer bootstrap.reset {};
@layer bootstrap, base {};

Un-Named Layers:

Since layering is determined by order of appearance, we could also support unnamed layers:

@layer url(reset.css);
@layer url(base.css);

@layer {
  /* the next layer */
}

@layer {
  /* and another */
}

While these layers behave exactly like named layers in every way, they do not provide a "hook" for merging or re-ordering @layer rules. In most use-cases this would only be syntax-sugar for brevity -- relying on well-organized source-order rather than any explicit names. However, it could be used by teams as a way to "force" an organizing convention (all layer code must be defined in one place), or by libraries wanting to merge & hid" a set of internal "private" layers that they don't want exposed to author manipulation:

/* bootstrap-base.css */
/* unnamed wrapper layers around each sub-file */
@layer url(base-forms.css);
@layer url(base-links.css);
@layer url(base-headings.css);

/* bootstrap.css */
/* the intrnal names are hidden from access, subsumed in "base" */
@layer base url(bootstrap-base.css);

/* author.css */
/* author has access to bootstrap.base layer, but not into unnamed layers */
@layer bootstrap url(bootstrap.css);

What is the migration path for Cascade Layers? #4985

Since this proposal defines Cascade Layers directly above Specificity in the cascade, but below inline style attributes, it should be possible to polyfill the entire feature using ID tags to boost specificity. Most simply stated:

#reset a { /* reset layer */ }
#base#base a { /* base layer */ }
#components#components#components a { /* component layer */ }

In order to avoid requiring a match with ID attributes in the HTML, that specificity can be generated using the :is() pseudo-class:

:is(#r, a) { /* reset layer */ }
:is(#b#b, a) { /* base layer */ }
:is(#c#c#c, a) { /* component layer */ }

The reality will require some additional finesse to avoid conflicts with existing ID selectors, but those details can be left to individual polyfills.

Refactor Use-Case:

We believe this proposal addresses all of the use cases discussed, with a few caveats around refactoring and overriding legacy styles. It would be nice for site maintenance to slot all the existing styles into a "legacy" layer, and then have any/all new styles in a higher priority layer. As new styles are added, they should always override the original legacy code. But there are some issues:

  1. In the normal author origin, unlayered styles will always take precedence over layered styles. Legacy code would need to be given an explicit layer -- but that can be done using the layer import syntax. This workaround is very manageable, but:
  2. In the !important author origin, layers are reversed. If legacy styles are given the lowest normal layering, any legacy !important styles will jump to the top layer, and become much harder to override.

This would require changes to any legacy uses of !important -- either manually, or using some kind of css transpiler -- moving normal rules in one layer, and !important rules into a different layer. Then both legacy layers can be individually placed at the bottom of their respective stacks.

This is a purely mechanical transformation that can be done server side, but if it needs to get syntax-error handling right, it may not be trivial to write.

Questions:

  • Does the loading order of style sheets matter? No, this is the same as existing source-order
  • Can user/UA stylesheets also use layers? Yes, this would be available in all origins
  • Can you nest layer blocks? Yes, sames as existing at-rules
  • Specificity is unchanged inside layers? Yes
  • If a stylesheet is loaded in multiple layers, is it both places? Yes, as with current duplicate imports

Needs Discussion:

  • What is the best syntax for layer imports?
  • What is the best syntax for nested layer names?
  • Are un-named layers a feature or a problem?
  • Do we need a way to revert layers as well as origins?
  • Does light-DOM layer-ordering impact shadow-DOM layers with the same names?
@brunoais

This comment has been minimized.

Copy link

@brunoais brunoais commented Aug 12, 2020

With this change, browser addons may become unable to override inline styles by using the !important forcing a use of harder to develop strategies. Did you take that into account?

@mirisuzanne

This comment has been minimized.

Copy link
Owner Author

@mirisuzanne mirisuzanne commented Aug 12, 2020

@brunoais I don't believe that's actually true. This proposal does not change the relationship between important & inline styles. Inline styles have always been at the top of both normal & important author origins. Adding !important has and will continue to work as an override for normal inline styles. It has never been possible to override styles that are both inline and important from a selector, and that remains true here. This is designed to be a non-breaking change that provides new features without removing any existing functionality.

Meanwhile this proposal would give browser addons the ability to insert new layers on either/both ends of the stack - making it simpler for them to override normal styles without even needing to rely on !important.

@Wolfr

This comment has been minimized.

Copy link

@Wolfr Wolfr commented Aug 12, 2020

@layer components {
  /* site base styles */
}

I believe this comment should read: site components.

@mirisuzanne

This comment has been minimized.

Copy link
Owner Author

@mirisuzanne mirisuzanne commented Aug 12, 2020

@Wolfr - yes, thank you! Fixed.

@andruud

This comment has been minimized.

Copy link

@andruud andruud commented Aug 13, 2020

What happens if you revert in a @layer?

@andruud

This comment has been minimized.

Copy link

@andruud andruud commented Aug 13, 2020

Also, are other at-rules (@keyframes, @property, etc) valid inside @layers? If yes I assume they also cascade according to the order defined by the layers?

@lilles

This comment has been minimized.

Copy link

@lilles lilles commented Aug 13, 2020

Since the layer order is defined by order of appearance, how does that work with multiple stylesheets?

If I have:

<link rel=stylesheet href=a.css>
<link rel=stylesheet href=b.css>

and:

a.css:
@layer a {}

b.css:
@layer b {}

c.css:
@layer b {}
@layer a {}

Will the layer order be a, b and will the order of the layers change if I insert a link with c.css before the other two links?

@pepelsbey

This comment has been minimized.

Copy link

@pepelsbey pepelsbey commented Aug 13, 2020

First of all, thank you for trying to keep the cascade part of CSS relevant and useful. Second, though it looks like something exciting, I’m still struggling to understand the use case. In proposals or a drafts like this I used to see an explainer of some sort at the beginning:

  • What problem does it solve
  • Existing alternative solutions
  • Code: before/after
  • Etc.

This one starts from its place in the cascade. But developers try to avoid the cascade as much as possible these days. So how this thing is going to fit, what problems it’s going solve? Maybe it’s just at early stage, but I’d suggest adding such intro before asking for a feedback from developers.

@mirisuzanne

This comment has been minimized.

Copy link
Owner Author

@mirisuzanne mirisuzanne commented Aug 13, 2020

@andruud -

  1. revert is a great question. There's been some discussion around that, but I don't think a clear conclusion. If we want a way to revert a single layer - that might need a new keyword, but I'm not sure. Adding it to the outstanding questions…
  2. Yes, other at-rules can be nested in layers, and would be treated as part of that layer.

@lilles -

Layers would be global, like all other CSS cascade/ordering. So yes, the file import order would (still) be meaningful, and would work the way you described.

@pepelsbey -

I agree that would be good to do at some point, but it's not really the purpose of this document. I'll write a full explainer at some point. For now you can find most of that information and discussions around it in the various linked CSSWG issues. That discussion has already been underway, with many use-cases discussed. This document is only attempting to answer the questions raised elsewhere, by providing a clear syntax proposal.

@andruud

This comment has been minimized.

Copy link

@andruud andruud commented Aug 13, 2020

FWIW, I think it would be a good choice to let revert (in any layer) revert back to the previous origin, not the previous origin-or-layer. I think what authors want from revert is "reset style to that provided by the UA". So if we make revert reset to the previous layer instead, authors are (probably) anyway going to ask for a new keyword that resets to the previous origin. And in that case I'd prefer that revert deals with origins only, and then add something new for revert-to-layer (if it's really needed).

I have some more questions:

  1. Are @layers scoped to their shadow tree? E.g. which color will this show?
<style>
  @layer base { }
  @layer main { }
</style>
<div>
  <#shadow-root>
    <style>
      @layer main { div { color: red; } }
      @layer base { div { color: green; } }
    </style>
    <div>Hello World</div>
  </#shadow-root>
</div>

  1. What happens if I use @layer in a user stylesheet? Will it then "split" the user origin similarly to how it works for author stylesheets / author origin?

  2. Can you nest @layers like this? (I did notice the @layer bootstrap base example, but I'm wondering whether it's allowed for an @layer to appear within an @layer).

 @layer foo {
    @layer bar {
      @layer foo {
         div { color: red; }
      }
    }
 }
  1. Specificity works like normal within each @layer, right?

I apologize for not having kept up with all the discussions on GitHub, some or all of those things have probably been covered already.

@chrishtr

This comment has been minimized.

Copy link

@chrishtr chrishtr commented Aug 14, 2020

What if a site wants to delay-load the stylesheet for a component library, and respect that library's base vs custom style layers. e.g.

<link rel=stylesheet src=bootstrap.css>
<style>
@layer customize {
.bootstrap-component {
  background: green;
}
</style>

bootstrap.css:
@layer bootstrap-base {
.bootstrap-component {
  background: red
}

If bootstrap.css loads after the inline style tag, then the component will render red, not green, which is not desired.

With this proposal, the only way to fix it would be that the developer has to pre-declare all layers:

@layer bootstrap-base {}
@layer customize {}

Developers may forget to do this, and it also keeps bootstrap from adding layers without risking them breaking on sites. Further, it is a bit of a software engineering abstraction violation that the site author needs to know about all the layers of a component. (If there were an @layer syntax on <link> elements, I suppose it could be solved also by placing a layer name on the stylesheet being loaded.)

For these reasons, it doesn't seem great to me that layer order is determined by stylesheet loading order. I think @lilles was implicitly making this point in a comment above as well.

This could also be resolved in common cases by predefining certain layers and encouraging a best practice of using those layer names when possible.

@chrishtr

This comment has been minimized.

Copy link

@chrishtr chrishtr commented Aug 14, 2020

What happens if the same stylesheet is loaded via multiple layers? Presumably this would mean the stylesheet is represented twice.

@chrishtr

This comment has been minimized.

Copy link

@chrishtr chrishtr commented Aug 14, 2020

This proposal also has the property that the layer/specificity of a style rule depends on not just the order of loading, but the method and nesting of loading. Example:

a.css:
@layer url(b.css)

b.css:
@layer url(c.css)

c.css:
.foo {
  background: green;
}

In this example, the .foo style rule has a double-anonymous layer name for it, and one whose ordering relative to other layers depends on when it was loaded relative to other layers defined outside of c.css. In other words, for a developer to understand how .foo applies, they will have to know about non-local details of how that style sheet is loaded.

It would be better if all of the information they needed was in the same block. That is, @layer { .foo { ...} } is much easier to understand and debug than action-at-a-distance @layer url(c.css).

@chrishtr

This comment has been minimized.

Copy link

@chrishtr chrishtr commented Aug 14, 2020

Here's another bad race condition that can happen:

a.css:
@layer url(b.css)
@layer(d.css)

b.css:
@layer url(c.css)

The order of loading off the network could be a, b d, c. This sounds like it will be confusing to developers, who might otherwise intuitively expect "depth-first" layer ordering.

@lilles

This comment has been minimized.

Copy link

@lilles lilles commented Aug 14, 2020

For these reasons, it doesn't seem great to me that layer order is determined by stylesheet loading order. I think @lilles was implicitly making this point in a comment above as well.

The order of the stylesheets does not rely on order of loading finished, but the dom and rule order within a stylesheet. But there is a concern around flipping order when non-render-blocking stylesheets finish loading. It's probably a good idea for authors to make sure sheets which are expected to define the order to come early and be render-blocking.

One concern is when you mix components which have different layer stacks, how they would be interleaved and to what extent the page author needs to be aware of layers in imported components. Name clashes could be an issue.

@brunoais

This comment has been minimized.

Copy link

@brunoais brunoais commented Aug 14, 2020

Isn't it the order in the DOM and then the stylesheet instead?
Just like now, if you us js to add a stylesheet to the <head> at the beginning, the results are the same as if it had been there all along.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.