Day 43: grouping layers

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


Cascade layers can be grouped by nesting layer rules.

If you work on a large style sheet, you might want to create cascade layers to group different types of declarations. In order to give your layers even more structure and control, you can also group declarations within layers.

Consider the following example. We have a layer for reset styles, base styles, components, and theming.

@layer reset {
  body {
    margin: 0;
  }
}

@layer base {
  body {
    font-size: 1.6rem;
  }
}

@layer components {
  p {
    border: 1px solid;
  }
}

@layer theme {
  p {
    border-color: red;
  }
}

There's nothing wrong with that, but it might make sense to group similar layers. For example, you could group reset and base styles and component and theme styles.

@layer base {
  @layer reset {
    body {
      margin: 0;
    }
  }

  @layer defaults {
    body {
      font-size: 1.6rem;
    }
  }
}

@layer components {
  @layer structure {
    p {
      border: 1px solid;
    }
  }

  @layer theme {
    p {
      border-color: red;
    }
  }
}

The same rules in terms or prioritization that apply to root layers also apply to nested layers. This adds more complexity to your style sheets, but it also gives you fine-grained control over specificity.

Nesting layer may seem to be overkill, and it probably is for many sites, but it will make more sense once we talk about ordering layers.

See on CodePen

Further reading

Do you want to learn even more awesome CSS?

I'm running a workshop with my friends at Smashing Magazine in which I introduce you to the most useful modern features in CSS and show how you can implement them today in your code base to improve scalability, maintainability, and productivity.

Learn more about the workshop!

Overview: 100 Days Of More Or Less Modern CSS