Understanding CSS Specificity: Resolving Conflicting Styles

Master CSS style precedence with this guide to CSS specificity. Learn how the browser determines which styles apply when multiple rules target the same element, covering selector types, specificity calculations, and techniques for controlling style application in your CSS.



Understanding CSS Specificity

What is CSS Specificity?

CSS specificity determines which CSS rule applies when multiple rules target the same HTML element. The browser uses a set of rules to determine which style takes precedence when conflicts occur (e.g., when the same property is defined in multiple CSS rules). Specificity helps resolve these conflicts and predict which style will be applied to an element.

Important Points About Specificity

  • Specificity matters only when multiple conflicting rules affect the same element.
  • If multiple selectors have the same specificity, the *last defined* rule wins.
  • Universal selectors (`*`) and inherited styles have the lowest specificity (0).
  • Inline styles have higher specificity than selectors (except when `!important` is used).
  • The `!important` declaration overrides all other specificity rules.

Specificity Hierarchy

CSS selectors have a hierarchical order of specificity:

  1. Inline styles: Styles applied directly within an HTML element's `style` attribute (highest priority).
  2. IDs: Styles targeting elements by their unique ID attribute (e.g., `#myElement`).
  3. Classes, attributes, and pseudo-classes: Styles targeting elements by class, attribute, or pseudo-classes (e.g., `.myClass`, `[type="text"]`, `:hover`).
  4. Elements and pseudo-elements: Styles targeting elements by tag name or pseudo-elements (e.g., `p`, `div`, `::before`, `::after`). These have the lowest priority.

Calculating Specificity

Specificity is calculated based on the types of selectors used. A more complex selector generally has higher specificity. The browser assigns a numerical weight to each selector type to determine which rule is most specific.

Examples Illustrating Specificity

These examples demonstrate how specificity works. You'd need corresponding HTML elements for these CSS rules to function correctly. The examples highlight situations where multiple rules affect the same element, illustrating how specificity determines which rule takes precedence.

Example 1: ID Selector vs. Attribute Selector

This example shows that an ID selector (`#myId`) has higher specificity than an attribute selector (`[type="text"]`).

Example 2: Multiple Rules with Equal Specificity

This illustrates that when multiple rules have the same specificity, the last-defined rule wins.

Example 3: Class Selector vs. Element Selector

This example shows that class selectors (e.g., `.myClass`) have higher specificity than element selectors (e.g., `div`, `p`, `h1`).