Open In App

How to use @layer rule to overcome cascading styles conflicts in CSS ?

A cascade layer is declared using the @layer CSS at-rule, which can also be used to specify the hierarchy of precedence when there are multiple cascade layers. With this, web developers have more control over cascades as a result of rules that layer cascades together. Any styles that are not in a layer are collected and added to a single anonymous layer that follows all named and anonymous layers that have been declared. This implies that regardless of their level of specificity, any styles declared outside of a layer will take precedence over those declared inside.                  

Approach:



Syntax: 

Single layer: In this, “layer-name” is the name of a particular layer and rules are the list of the CSS rules for the layer.



    @layer layer-name {rules}

Multiple layer: For defining multiple layers, we use the above syntax and  their  precedence is from left to right which means the highest precedence is to the right most layer.

 @layer layer-name-1, layer-name-2, layer-name-3;

Example 1: Lets see an example of how anonymous layers precedence is greater than any defined layer. 

HTML Code:




<!DOCTYPE html>
<html>
<head>
    <title>Layers</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="gfg-container">
        <p>Welcome to Geeks For Geeks</p>
    </div>
</body>
</html>

CSS Code: The following code is the “style.css” which is used above.




p {
  color: green;
}
 
@layer gfgExample {
  .gfg-container{
    font-weight: bold;
    font-size: 20px;
    color: black;
    background-color: grey;
  }
}

Output:

@layer at-rule

Example 2:  Let us see an example without any anonymous layers.

HTML Code:




<!DOCTYPE html>
<html>
<head>
    <title>Layers</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="gfg-container">
        <h1>Welcome to Geeks For Geeks</h1>
    </div>
</body>
</html>

CSS Code:




@layer first, second;
       
@layer second{
.gfg-container h1 {
  color: green;
  }
}
 
@layer first {
  .gfg-container h1 {
    font-weight: bold;
    font-size: 20px;
    color: black;
    border: 2px solid darkgreen;
  }
}

Output:

@layer at-rule precedence order


Article Tags :