CSS Tutorial

CSS Specificity

Understanding CSS Specificity

CSS specificity determines which styles override others. It's calculated based on the following rules:

  • Inline styles (e.g., style="color: red") have the highest specificity.
  • ID selectors (e.g., #header) have the next highest specificity.
  • Class selectors (e.g., .header) have lower specificity than ID selectors.
  • Element selectors (e.g., header) have the lowest specificity.

Calculating Specificity

Specificity is calculated using a 3-part system:

  • Count the number of ID selectors: Each ID selector adds 100 to the specificity.
  • Count the number of class selectors, attribute selectors, and pseudo-classes: Each of these selectors adds 10 to the specificity.
  • Count the number of element selectors: Each element selector adds 1 to the specificity.

Example:

The following CSS rules have the following specificity:

  • #header { color: red; } (Specificity: 100)
  • .header { background: blue; } (Specificity: 10)
  • header { font-size: 16px; } (Specificity: 1)

Understanding Style Conflicts

The CSS rule with the highest specificity will be applied. In the example above, the inline style on the <header> element overrides the other two rules because it has a higher specificity.

Steps to Avoid Style Conflicts

  • Use specific selectors to target elements more precisely.
  • Avoid using inline styles if possible.
  • Use ID selectors sparingly and only for unique elements.
  • Use class selectors for elements that share similar styles.
  • Understand how specificity is calculated.

By following these steps, you can ensure that your CSS styles are applied as intended and avoid unintended conflicts.