Cover Image for CSS Specificity
145 views

CSS Specificity

CSS specificity is a concept that determines which CSS rule takes precedence when multiple rules target the same element. When there are conflicting styles for an element, the browser needs to decide which style should be applied. The specificity of a selector is a measure of how “specific” it is, and it determines the weight of the selector in the conflict resolution process.

Specificity is calculated using four components:

  1. Inline Styles: Styles defined directly in the HTML using the style attribute have the highest specificity.
  2. ID Selectors: Selectors targeting an element by its unique ID have a higher specificity than class selectors.
  3. Class Selectors, Attribute Selectors, and Pseudo-Classes: These selectors have the same specificity. They target elements by their class names, attributes, or pseudo-classes (e.g., :hover, :first-child).
  4. Type Selectors and Pseudo-Elements: These selectors have the lowest specificity. They target elements by their tag names or create pseudo-elements (e.g., ::before, ::after).

When comparing two or more conflicting rules, the browser assigns a specificity value to each selector based on the above components. A higher specificity value means the rule is more specific and takes precedence over rules with lower specificity.

The specificity is usually represented as a four-part value, known as the specificity hierarchy: a, b, c, d, where:

  • a represents the number of inline styles,
  • b represents the number of ID selectors,
  • c represents the number of class selectors, attribute selectors, and pseudo-classes, and
  • d represents the number of type selectors and pseudo-elements.

Example:

Consider the following CSS rules:

/* Rule 1 */
p {
  color: red;
}

/* Rule 2 */
#special-paragraph {
  color: blue;
}

/* Rule 3 */
p.special {
  color: green;
}

Suppose we have the following HTML:

<p class="special" id="special-paragraph">This is a special paragraph.</p>

In this example:

  • Rule 1 (p) has a specificity of 0, 0, 1, 0.
  • Rule 2 (#special-paragraph) has a specificity of 0, 1, 0, 0.
  • Rule 3 (p.special) has a specificity of 0, 0, 2, 0.

Therefore, Rule 3 takes precedence over Rule 1, and Rule 2 takes precedence over both Rule 1 and Rule 3 because it has the highest specificity.

Understanding specificity is crucial for writing maintainable and predictable CSS. When encountering specificity issues, it’s essential to use selectors wisely and avoid overly specific rules when possible. If needed, consider restructuring the HTML or using more specific class names to achieve the desired styling without excessive specificity.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS