MakeW3web

CSS Specificity

CSS specificity is a concept that determines which CSS rule applies to an element when there are multiple conflicting rules.

Specificity is calculated based on the selectors used in a CSS rule. Each selector has a specificity value, and the more specific a selector is, the higher its specificity value.

For example, a CSS rule that targets an element using an ID selector (e.g. #header) is more specific than a CSS rule that targets the same element using a class selector (e.g. .header), because ID selectors have a higher specificity value than class selectors.

Here's a breakdown of the specificity values for different types of selectors:

  • ID selectors have a specificity value of 100.
  • Class selectors, attribute selectors, and pseudo-classes have a specificity value of 10.
  • Type selectors and pseudo-elements have a specificity value of 1.

When two or more conflicting CSS rules target the same element, the rule with the highest specificity value wins.

For example, consider the following CSS rules

#header {
  background-color: red;
}

.header {
  background-color: blue;
}

If the element has an ID of "header" and a class of "header", the first rule will apply because it has a higher specificity value than the second rule.

However, if the element only has a class of "header", the second rule will apply because it is the only rule that applies to the element.

It's important to understand CSS specificity to avoid unexpected styling conflicts and to write more efficient CSS code. Here are some best practices to keep in mind:

  • Avoid using ID selectors in your CSS as much as possible, as they can lead to specificity wars and make your code harder to maintain.
  • Use classes and attribute selectors to target elements instead of IDs, and make sure to use specific class names that describe the element's purpose (e.g. .nav instead of .header).
  • If you need to increase the specificity of a selector, use nested selectors instead of ID selectors (e.g. .header .logo instead of #header .logo).
  • Use !important sparingly, as it overrides all other rules and can make your code harder to debug.
Was this page helpful?