「CSS Cascading and Inheritance Level 4」相關筆記

總結

此篇為 CSS cascading 與 specificity 的相關筆記,來源為 W3C、MDN 與 CSS-Tricks 文章

The cascade and specificity are mechanisms that control which rule applies when there is such a conflict.

筆記

Introduction

Value Processing

The final value of a CSS property for a given element or box is the result of a multi-step calculation(所有的 CSS 樣式最終都會變為以 px 為單位的數值)

  1. First, all the declared values applied to an element are collected, for each property on each element. There may be zero or many declared values applied to the element. 同一個元素可能被宣告多種樣式

  2. Cascading yields the cascaded value. There is at most one cascaded value per property per element. 透過 cascading 將一元素的樣式縮減為僅有一個的 cascaded value

  3. Defaulting yields the specified value. Every element has exactly one specified value per property.

  4. It is the result of putting the cascaded value through the defaulting processes, guaranteeing that a specified value exists for every property on every element.

  5. In many cases, the specified value is the cascaded value.

  6. However, if there is no cascaded value at all, the specified value is defaulted.

  7. 如果沒有 cascaded value 則透過 initial 或 inherit 取得樣式

  8. Resolving value dependencies yields the computed value. Every element has exactly one computed value per property. 將 relative value(比如原本以 rem 為單位的數值)轉為固定數值

  9. relative units: em, ex, vh, vw

  10. certain keywords (e.g., smaller, bolder) must be replaced according to their definitions

  11. percentages on some properties must be multiplied by a reference value (defined by the property)

  12. Formatting the document yields the used value. An element only has a used value for a given property if that property applies to the element. 根據 layout 來計算 used value,比如width: auto;要根據畫面最終 layout 才能計算出auto的實際數值

  13. Finally, the used value is transformed to the actual value based on constraints of the display environment. As with the used value, there may or may not be an actual value for a given property on an element. 瀏覽器等裝置最後使用的數值

    How CSS values are processed Examples of CSS Value Computation

Cascade

When equal specificity, order matters.

Specificity

When different styles apply to same element, which wins.

Defaulting

No cascaded value? Ask defaults.

Explicit Defaulting

除了initialinherit以外還有另外兩種關鍵字可以使用

The definitive guide to CSS styling order

參考文件