css 樣式——後面覆蓋前面

zhiwei發表於2017-12-20

上程式碼

<div class="red yellow" style="height:200px; width: 200px;"><div>
.yellow {
    background: yellow;
}

.red {
    background: red;
}

這個區域渲染出來是什麼顏色呢?紅色? 黃色?

答案是紅色

不知道有多少人和我有一樣的誤區,一直以為是由class中的排版順序決定同優先順序樣式應用順序的。。。

實際上是誰在css檔案中,權重相等,宣告在後面,那麼最終就應用誰

解釋

W3C 上面的說明
https://www.w3.org/TR/CSS2/cascade.html#cascading-order

Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.

大致意思就是,如果兩個選擇器的宣告權重相等,那麼誰在後面,最後就應用誰。

相關文章