24. What is specificity in CSS and how does it work in case of style conflicts?

Specificity determines which styles take precedence in case of conflicts. Higher specificity overrides lower specificity.

  • Number of IDs (Highest specificity): Each ID selector in the rule increases specificity by 100.

    • Example: #element has higher specificity than .class.
  • Number of classes and attributes: Each class or attribute in the selector increases specificity by 10.

    • Example: .class has higher specificity than element.
  • Number of elements and pseudo-classes: Each element or pseudo-class (e.g., :hover) in the selector increases specificity by 1.

    • Example: div has higher specificity than :hover.
  • !important (Highest specificity): The CSS declaration value with !important has the highest specificity and always overrides other styles.

If there is a conflict between styles, the browser will apply the rules with higher specificity. If the specificity is the same, the browser will apply the rules that appear later in the code (cascade rule).

Examples of Specificity:

  • #element is more specific than .class.
  • .class1.class2 is more specific than .class1.
  • div p is more specific than p.
  • .class !important has the highest specificity and always takes precedence.

Understanding specificity correctly is crucial to avoid unexpected conflicts in CSS code and effectively control which styles will be applied to HTML elements. In practice, it is recommended to avoid overusing !important and creating overly complex selectors to maintain readability and control over the CSS code.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.