Day 58: ordering nested 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.


On day 43, we've learned how to group layers and on day 46, how to order them. In this post, we’ll look into ordering grouped layers.

If we take the following layer, the background color of the <p> will be red because the last defined layer has precedence over previously defined layers.

@layer base {
  @layer reset {
    p {
      background-color: #fff;
    }
  }

  @layer theme {
    p {
      background-color: aqua;
    }
  }

  @layer defaults {
    p {
      background-color: red;
    }
  }
}

yo!

We can change the order by defining the layers within the base layer upfront.

@layer base {
  @layer reset, defaults, theme;

  @layer reset {
    p {
      background-color: #fff;
    }
  }

  @layer theme {
    p {
      background-color: aqua;
    }
  }

  @layer defaults {
    p {
      background-color: red;
    }
  }
}

reset has the lowest priority and theme the highest.

yo!

If we move the list outside of the base layer, our custom order has no effect because the layers in the list only exist inside the base layer.

@layer reset, defaults, theme;
@layer base {
  @layer reset {
    p {
      background-color: #fff;
    }
  }

  @layer theme {
    p {
      background-color: aqua;
    }
  }

  @layer defaults {
    p {
      background-color: red;
    }
  }
}

yo!

If we want to change the order inside a layer from the outside, we can do that by referencing the nested layer on the parent layer, similar to how you would reference a property in a JavaScript object.

@layer base.reset, base.defaults, base.theme;
@layer base {
  @layer reset {
    p {
      background-color: #fff;
    }
  }

  @layer theme {
    p {
      background-color: aqua;
    }
  }

  @layer defaults {
    p {
      background-color: red;
    }
  }
}

yo!

If we add another parent layer to the mix, you can see how the background color is hotpink even though we’ve added the component.first layer early in the list. That’s because top level layers are sorted first, and then the layers within each layer group. The parent layer component has precedence over the base layer because it comes later in the list.

@layer base.reset, component.first, base.defaults, base.theme;
@layer base {
  @layer reset {
    p {
      background-color: #fff;
    }
  }

  @layer theme {
    p {
      background-color: aqua;
    }
  }

  @layer defaults {
    p {
      background-color: red;
    }
  }
}

@layer component {
  @layer first {
    p {
      background-color: hotpink;
    }
  }
}

yo!

See on CodePen

Further reading

Overview: 100 Days Of More Or Less Modern CSS