Search code examples
csscss-specificitycss-cascadecss-importcss-layer

Background color overridden even after reversing the order of CSS layers


I want to use the new CSS cascade layers feature supported by latest versions of Chrome, Firefox, Safari, and Edge (see the support table).

I'm importing a stylesheet from highlight.js. It has a class named hljs that applies a background color to <code> elements. I want to override that color with CSS @layer rules:

@import url("styles/base16/google-light.min.css") layer(highlightjs);

@layer highlightjs, main;

@layer main {
  .hljs {
    background: red;
  }
}

This works and overrides the background color but when I reverse the order of layers, still my background color applies. Why is that?

@layer main, highlightjs;

Solution

  • The issue is that your @import provides the first naming of the "highlightjs" layer. It comes before the list of layers, so it makes it the lowest precedence layer. The list of two layers then has no effect.

    @import url("data:text/css, code { background:blue; color:yellow }") layer(highlightjs);
    
    @layer main, highlightjs;
    
    @layer main {
      .hljs {
        background: red;
      }
    }
    <code class="hljs">
      Hello World
    </code>

    For this reason, an @layer list is allowed to precede an @import. In the snippet below, the order of layers is main, then highlightjs, and the colouring is adjusted appropriately.

    @layer main, highlightjs;
    
    @import url("data:text/css, code { background:blue; color:yellow }") layer(highlightjs);
    
    @layer main {
      .hljs {
        background: red;
      }
    }
    <code class="hljs">
      Hello World
    </code>