Basics
CSS Specificity
Understanding CSS Specificity
CSS specificity determines style priority, with !important as a last resort.
What is CSS Specificity?
CSS specificity is a set of rules applied to CSS selectors that determine which styles are applied to an element. It is a crucial part of the CSS cascade that helps resolve conflicts when multiple styles target the same element. Understanding specificity helps developers write efficient and predictable CSS.
Calculating Specificity
Specificity is calculated based on the types of selectors used. Here is a simple breakdown of how specificity is calculated:
- Inline styles (e.g.,
style=""
) have the highest specificity. - ID selectors (e.g.,
#example
) have high specificity. - Class selectors (e.g.,
.example
), attributes (e.g.,[type="text"]
), and pseudo-classes (e.g.,:hover
) have moderate specificity. - Element selectors (e.g.,
div
) and pseudo-elements (e.g.,::before
) have low specificity.
Specificity Hierarchy Example
The following example demonstrates how different selectors with varying specificity affect the style applied to a paragraph element:
In this example, the #unique
ID selector takes precedence over the class and element selectors, resulting in the text being red.
The Role of !important
The !important
rule can override any specificity conflicts by giving a style absolute priority. It should be used sparingly as it makes CSS harder to maintain.
In this case, the !important
rule on the element selector forces the text to be blue, despite the ID selector's higher specificity.
Best Practices for Managing Specificity
To efficiently manage CSS specificity, consider these best practices:
- Avoid using
!important
unless absolutely necessary. - Use IDs sparingly and prefer class selectors for styling.
- Keep your CSS selectors as simple as possible to avoid specificity conflicts.
- Consider using CSS preprocessors like SASS or LESS to manage and automate specificity.
Basics
- Previous
- Combinators
- Next
- Cascade