層疊樣式表 (CSS) 是 Web 的基礎技術,可讓開發人員控制 HTML 文件的視覺呈現。雖然 CSS 語法乍看之下似乎很簡單,但應用和繼承樣式的方式可能出奇地複雜。理解這些複雜性對於編寫高效、可維護和可預測的 CSS 至關重要。
在這份綜合指南中,我們將探討 CSS 的級聯和繼承概念。
級聯是當存在多個衝突規則時決定將哪些 CSS 規則應用於元素的演算法。了解級聯的工作原理對於編寫按預期運行的 CSS 至關重要。級聯依以下順序考慮多個因素:
為了完全詳盡,我們可以加入:
讓我們以優先順序分解影響級聯的因素:
CSS 可以來自三個不同的來源:
通常,作者樣式優先於使用者樣式,而使用者樣式會覆寫使用者代理樣式。這允許開發人員自訂元素的外觀,同時在必要時仍尊重使用者的偏好。
使用 style 屬性直接應用於元素的樣式具有非常高的優先權:
<p style="color: red;">This text will be red.</p>
內嵌樣式將覆蓋外部樣式表或
使用內聯樣式通常不鼓勵,因為它將演示與內容混合在一起並使樣式更難維護。
特異性是CSS中的關鍵概念,它決定了當存在多個衝突規則時將哪些樣式應用於元素。每個 CSS 選擇器都有一個特異性編號,可以透過計算該編號來預測哪些樣式將優先。
特異性通常表示為四部分數字 (a,b,c,d),其中:
結果數字不是以 10 為基數。相反,請將其視為從左到右比較的單獨欄位。請參閱範例:
考慮這兩個相互衝突的規則:
#header .nav li { color: blue; } /* (0,1,1,1) */ nav > li a { color: red; } /* (0,0,0,3) */
第一條規則 (0,1,1,1) 具有更高的特異性,因此文本將為藍色。
偽類選擇器(例如 :hover)和屬性選擇器(例如 [type="text"])都具有與類別選擇器相同的特異性。
通用選擇器 (*) 和組合符 (>, +, ~) 不影響特異性。
此外,:not() 偽類也不會增加特異性值;只計算其中的選擇器。
一些線上工具可以幫助計算特異性 (https://specity.keegan.st/)。
如果其他條件相同,則樣式表中稍後出現的規則優先:
.button { background-color: blue; } .button { background-color: green; } /* This one wins */
在此範例中,按鈕將具有綠色背景。
雖然理解級聯對於編寫可維護的 CSS 至關重要,但還有一個難題可以覆蓋我們迄今為止討論的所有規則:!important 關鍵字。
!important 關鍵字可以覆寫級聯中的所有其他注意事項,除了其他具有更高來源優先權的 !important 宣告。
/* styles.css */ .button { background-color: blue !important; }
<!-- index.html --> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <button style="background-color: red"> My button </button> <!-- The color will be blue due to !important above --> </body>
In this example, even though inline styles usually have the highest priority, the button will still have a blue background because of the !important declaration.
The !important keyword actually introduces additional layers to the cascade. The full order of precedence, from highest to lowest, is:
While !important can be tempting as a quick fix, it's generally considered a last resort. Overuse can lead to specificity wars and make your CSS harder to maintain. Legitimate use cases include:
If you find yourself using !important often, consider refactoring your CSS to use more specific selectors or a more modern approach like utilising :is() and :where() to write more flexible and maintainable styles. (I talk about these two in more details here)
Also, the @layer at-rule, which is fairly supported, allows you to create "layers" of styles with explicitly defined order of precedence:
@layer base, components, utilities; @layer utilities { .btn { padding: 10px 20px; } } @layer components { .btn { padding: 1rem 2rem; } }
This offers a more structured approach to managing style precedence without resorting to !important or engaging in a specificity arms race. However, I haven’t used this in a production project myself, if you do, I’d love to hear about your experience :)
Inheritance is another fundamental concept in CSS. Some CSS properties are inherited by default, meaning child elements will take on the computed values of their parents. This is particularly useful for text-related properties like color, font, font-family, font- size, font-weight, font-variant, font-style, line-height, letter-spacing, text-align, text-indent, text-transform, white-space, and word-spacing.
body { font-family: Arial, sans-serif; color: #333; line-height: 1.5; }
In this example, all text within the body will inherit these styles unless explicitly overridden. This allows for efficient styling of document-wide typography without having to repeat rules for every element.
A few others inherit as well, such as the list properties: list-style, list-style-type, list-style-position, list-style-image, and some other table related properties
Not all properties are inherited by default. For example, border and padding are not inherited, which makes sense – you wouldn't want every child element to automatically have the same border as its parent.
CSS provides several keywords to give you fine-grained control over inheritance and to reset styles:
The initial and unset keywords override all styles, affecting both author and user-agent stylesheets. This means they reset the element's styling to its default state, ignoring any previous styling rules applied by the author or the browser.
However, there are scenarios where you only want to reset the styles you’ve defined in your author stylesheet, without disturbing the default styles provided by the browser (user-agent stylesheet). In such cases, the revert keyword is particularly useful. It specifically reverts the styles of an element back to the browser’s default styles, effectively undoing any custom author-defined styles while preserving the inherent browser styling.
請注意,使用速記屬性時省略的值會隱式設定為其初始值。 這可能會覆蓋您在其他地方設定的其他樣式。
透過理解級聯、繼承和現代 CSS 功能的複雜性,您將能夠更好地編寫高效、可維護且強大的樣式表。請記住,CSS 不僅僅是讓事物看起來更漂亮,它還在於創建可在各種設備和瀏覽器上工作的健壯、靈活的設計。
以上是掌握 CSS:了解級聯的詳細內容。更多資訊請關注PHP中文網其他相關文章!