marp-team / marpit

The skinny framework for creating slide deck from Markdown
https://marpit.marp.app/
MIT License
964 stars 46 forks source link

`cascadeLayer` constructor option to render CSS with cascade layers #321

Open yhatt opened 2 years ago

yhatt commented 2 years ago

This suggestion is the framework-level support for dealing with subtle problems about style overloading like https://github.com/marp-team/marp-core/issues/244. @layer at-rule in a new CSS proposal about cascade layers makes the order of styling be controlled.

Why?

CSS rendering in Marpit relies to the order of appearance: @import -> the scaffold theme -> theme CSS -> inline styles + scoped styles (mixed) -> styles for the advanced background

This was fragile approach because easy to break the styling priority by CSS specificity.

For example, if there was example theme like this:

/* @theme example */

section {
  background: #fff;
  color: #000;
}

section.invert {
  background: #000;
  color: #fff;
}

A following tweak will not work because of low specificity.

---
theme: example
class: invert
---

<style>
section {
  background: #666;
}
</style>

A pre-released Marp Core v3 has fixed this problem by using :where pseudo-class (https://github.com/marp-team/marp-core/issues/244). But this approach is not so intuitive for custom theme authors.

An another broken case is the scoped style (<style scoped>). Users always would expect that styles in <style scoped> makes overriding styles defined in the theme CSS. However, a simple selector to section in <style scoped> (0-1-1 specificity) is not working against the section selector with 2+ classes (0-2-1 specificity).

<!-- class: a b -->

<style>
section.a.b {
  background: blue;
}
</style>

<style scoped>
section {
  /* Not working */
  background: red;
}
</style>

If supported CSS rendering with @layer, Marpit can make a border between the global style and slide-scoped style without no side effects. The slide author does no longer need to take care of the specificity.

Proposal

Add cascadeLayer constructor option to enable CSS rendering with cascade layers (@layer). The proposal of CSS cascade layers is still experimental in real world browsers, so cascadeLayers option should be disabled by default.

If cascadeLayer was enabled, styles added by the framework (and extended plugins) must try to contain in any @layer.

ToDo

Resources

Difference from Marpit v3 proposal

If you had seen the proposal of Marpit v3 in #194, you might know about the concept of "Contents layer". It is using the same word "layer", but they have different goals.