首頁 > web前端 > css教學 > 主體

掌握 CSS:了解級聯

WBOY
發布: 2024-07-17 09:33:39
原創
494 人瀏覽過

Mastering CSS: Understanding the Cascade

層疊樣式表 (CSS) 是 Web 的基礎技術,可讓開發人員控制 HTML 文件的視覺呈現。雖然 CSS 語法乍看之下似乎很簡單,但應用和繼承樣式的方式可能出奇地複雜。理解這些複雜性對於編寫高效、可維護和可預測的 CSS 至關重要。
在這份綜合指南中,我們將探討 CSS 的級聯和繼承概念。

CSS 級聯

級聯是當存在多個衝突規則時決定將哪些 CSS 規則應用於元素的演算法。了解級聯的工作原理對於編寫按預期運行的 CSS 至關重要。級聯依以下順序考慮多個因素:

  • 1 樣式表來源
  • 2 種內嵌樣式
  • 3 選擇器特異性
  • 4 來源訂單

為了完全詳盡,我們可以加入:

  • 2.5 在圖層中定義的樣式閱讀更多
  • 3.5 作用域為 DOM 一部份的樣式閱讀更多

讓我們以優先順序分解影響級聯的因素:

1. 樣式表起源

CSS 可以來自三個不同的來源:

  • 1 使用者代理樣式:這些是瀏覽器的預設樣式。每個瀏覽器都有自己的一組預設樣式,這就是為什麼無樣式的 HTML 在不同瀏覽器中看起來會略有不同。
  • 2 使用者樣式:這些是使用者設定的自訂樣式。雖然很少見,但某些使用者可能會使用自訂樣式表來覆寫預設樣式以實現可存取性或個人偏好。
  • 3 作者樣式:這些是您作為 Web 開發人員所寫的樣式。

通常,作者樣式優先於使用者樣式,而使用者樣式會覆寫使用者代理樣式。這允許開發人員自訂元素的外觀,同時在必要時仍尊重使用者的偏好。

2. 內聯樣式

使用 style 屬性直接應用於元素的樣式具有非常高的優先權:

<p style="color: red;">This text will be red.</p>
登入後複製

內嵌樣式將覆蓋外部樣式表或

使用內聯樣式通常不鼓勵,因為它將演示與內容混合在一起並使樣式更難維護。

3. 選擇器特異性

特異性是CSS中的關鍵概念,它決定了當存在多個衝突規則時將哪些樣式應用於元素。每個 CSS 選擇器都有一個特異性編號,可以透過計算該編號來預測哪些樣式將優先。

特異性通常表示為四部分數字 (a,b,c,d),其中:

  • a:內聯樣式數(一般省略)
  • b:ID選擇器的數量
  • c:類別選擇器、屬性選擇器和偽類的數量
  • d:元素選擇器和偽元素的數量

結果數字不是以 10 為基數。相反,請將其視為從左到右比較的單獨欄位。請參閱範例:

  • p = (0,0,0,1)
  • .class = (0,0,1,0)
  • #id = (0,1,0,0)
  • 行內樣式 = (1,0,0,0)

考慮這兩個相互衝突的規則:

#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/)。

4. 來源順序

如果其他條件相同,則樣式表中稍後出現的規則優先:

.button { background-color: blue; }
.button { background-color: green; }  /* This one wins */
登入後複製

在此範例中,按鈕將具有綠色背景。

強大的覆蓋

雖然理解級聯對於編寫可維護的 CSS 至關重要,但還有一個難題可以覆蓋我們迄今為止討論的所有規則:!important 關鍵字。

!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 Cascade and !important

The !important keyword actually introduces additional layers to the cascade. The full order of precedence, from highest to lowest, is:

  • User agent important declarations
  • User important declarations
  • Author important declarations
    • Important Inline styles
    • Important not inlined styles
  • Author normal declarations
    • Inline styles
    • Not inlined styles
  • User normal declarations
  • User agent normal declarations

When to Use it

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:

  • Overriding third-party styles you can't modify
  • Creating utility classes that should always apply
  • Ensuring critical accessibility styles are applied

A Potential Solution To Simplify Specificity Management

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

Passing Styles Down the DOM Tree

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.

Inheritance keywords

CSS provides several keywords to give you fine-grained control over inheritance and to reset styles:

  • The inherit keyword forces a property to inherit its value from its parent element (This can be useful for properties that don't inherit by default, like border in this example).
  • The initial keyword resets a property to its initial value as defined by the CSS specification (This can be helpful when you want to completely reset an element's styling).
  • The unset keyword acts like inherit for inherited properties and initial for non-inherited properties (This provides a flexible way to reset properties without needing to know whether they're inherited or not).
  • The revert keyword resets the property to the value it would have had if no author styles were applied (This is useful when you want to fall back to browser defaults rather than CSS-defined initial values).

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!