# [CSS] @layer ###### tags: `CSS` :::info * [瀏覽器支援度](https://caniuse.com/mdn-css_at-rules_layer):IE 不支援,其他主流瀏覽器在 2022 年初陸續支援 ::: * 改善過去不斷的堆疊選取器,提高優先權去覆寫前面其他選取器的優先權的情況 * 適合用在修改 component 預設樣式或是處理 Bootstrap 樣式 * 順序規劃可參考:@layer 基本 CSS, 共用 CSS, 組件 CSS * 例:`@layer libraries, base, common, layout, xxxxcomponent` ## 子 layer 寫法 ```css /* 寫法一 巢狀 */ @layer parent { @layer child { } } /* 寫法二 */ @layer parent {} @layer parent.child {} ``` ## 優先權 ### 在沒有 `!important` 的情況下 * non-layer 高於 layer * 父 layer 高於子 layer * 可以將 component 的設定寫在子 layer,覆寫的樣式寫在父 layer * 後面的 layer 高於前面的 layer * 建議 layer 撰寫順序從優先權小寫到大,或是在開頭先宣告順序 * 依照 `@layer` 宣告的順序 * 例:假設目前有 `layer1`、`layer2`、`layer3`,原始碼撰寫順序如下 ```css @layer layer1 { /* ... */ } @layer layer3 { /* ... */ } @layer layer2 { /* ... */ } ``` * `@layer layer2, layer3, layer1;`,優先權大至小為 `layer1` > `layer3` > `layer2` * `@layer layer2, layer1;`,優先權大至小為 `layer3` > `layer1` > `layer2` * layer 內採用選取器基本優先權 ### 如果屬性值有 `!important` * 反轉優先權,原本最小的變最大 * 以前者優先,先讀到 `!important` 就優先 #### 範例 ```htmlembedded <div class="box">Box</div> ``` ##### 1. 後面的 layer 高於前面的 layer,文字顏色為 blue ```css @layer layer1 { .box { color: red; } } @layer layer2 { .box { color: blue; } } ``` ##### 2. layer1 有 `!important`,文字顏色為 red ```css @layer layer1 { .box { color: red !important; } } @layer layer2 { .box { color: blue; } } ``` ##### 3. 兩個 layer 都有 `!important`,以前者優先,文字顏色為 red ```css @layer layer1 { .box { color: red !important; } } @layer layer2 { .box { color: blue !important; } } ``` ##### 4. layer 有 `!important`,文字顏色為 red ```css .box { color: yellow; } @layer layer1 { .box { color: red !important; } } ``` ##### 5. non-layer 和 layer 都有 `!important`,以 layer 優先,兩個 layer 以前者優先,文字顏色為 red ```css .box { color: yellow !important; } @layer layer1 { .box { color: red !important; } } @layer layer2 { .box { color: blue !important; } } ``` ##### 6. 父子 layer 都有 `!important`,以子 layer 優先,文字顏色為 pink ``` @layer parent { .box { color: purple !important; } @layer child { .box { color: pink !important; } } } ``` ##### 7. inline style 有 `!important`,文字顏色為 orange ```htmlembedded <div class="box" style="color: orange !important;">Box</div> ``` ```css @layer layer1 { .box { color: red !important; } } ``` ## 參考資料 * [@layer你不知道的CSS優先權!ID、class、tag,@layer又是甚麼?](https://youtu.be/H3uvgwFSgtg) --- :::info 建立日期:2023-03-27 更新日期:2024-02-25 :::