[CSS] @layer

Browser support: https://caniuse.com/?search=layer

As we know by defualt, class selector has a higher priority than element selector in CSS

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        color: red; <!-- should show in red -->
      }
      div {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h2>CSS @layer (CSS级联层)</h2>
    <div class="box">hello world</div>
  </body>
</html>

 

But when you use @layer, then the layer has a lower priority, only exceptipon is !important

    <style>
      @layer {
        .box {
          color: red;
        }
      }
      div {
        color: blue; /* 优先级高 */
      }
    </style>
    <style>
      @layer {
        .box {
          color: red !important; /* 优先级高 */
        }
      }
      div {
        color: blue; 
      }
    </style>

 

When you define multi @layer, then later one has higher priority

    <style>
      @layer theme, page; /* 越是后面的优先级越高, page has higher priority */
      @layer page {
        div {
          color: red; /* show in red */ 
        }
      }
      @layer theme {
        .box {
          color: blue;
        }
      }
    </style>

 

Usecase:

Normally in our application, we might use 3rd-party library, sometime the css it provides has a higher priority than the application css. 

To resolve that issue, in our application, we have to write complex CSS selector in order to override the 3rd-party library CSS.

For example:

<!-- In our application-->
    <style>
      @import url('./antd.css');
      div {
        color: blue;
      }
    </style>

<!-- 3rd-party lib filename: antd.css -->
.box {
  color: red;
}

In the case above, the colorshould be in red, due to in the 3rd-party lib, it has class selector, but we have only element selector.

By using @layer, we can resolve that issue:

    <style>
      @import url('./antd.css') layer;
      div {
        color: blue;
      }
    </style>
  </head>

 

posted @ 2025-05-25 18:38  Zhentiw  阅读(12)  评论(0)    收藏  举报