学习库CSSCascade and Specificity

Cascade and Specificity

Predict which declaration wins using origin, layer, specificity, scope, and order.

更新于 适用于 Modern CSS

When several declarations target the same property, the cascade resolves the conflict. Understanding that decision removes the need for selector escalation and repeated !important.

How a winner is chosen

The browser considers relevance, origin and importance, cascade layer, specificity, scoping proximity, then source order. For ordinary author styles in one layer, specificity and source order are what you see most often.

cascade.css
.notice { color: #4c1c62; }
main .notice { color: #211a25; }
.notice { color: #f46537; }

The descendant selector is more specific, so its color wins. If specificity ties, the later declaration wins.

Keep specificity low

layers.css
@layer reset, base, components, utilities;

@layer base {
  a { color: rebeccapurple; }
}

@layer components {
  .button { color: white; background: #4c1c62; }
}

Layers define a deliberate priority before specificity is compared. Low-specificity selectors such as :where(.card h2) are easy to override.

Inheritance

Some properties, including color and font-family, inherit from a parent. Box properties such as margin and border generally do not.

inheritance.css
body { color: #211a25; font-family: system-ui; }
button { font: inherit; }

Keep this

Design a low-specificity cascade, use layers for large systems, and let inheritance carry shared text styles.

学习位置已保存在此设备上。