Explain the concept of the CSS Specificity Hierarchy
Last Updated :
29 Jan, 2024
Cascading Style Sheets (CSS) is a powerful styling language that allows developers to control the presentation of HTML documents. One crucial aspect of CSS is specificity, which defines the rules for determining which styles will be applied to an element when conflicting styles exist. Let’s dive into the concept of the CSS specificity hierarchy and explore how it influences the cascade.
Basis of Specificity
CSS specificity is a measure of how specific a style rule is. The more specific a rule, the higher its specificity. Specificity is calculated based on four components:
- Inline Styles: Styles applied directly to an HTML element using the
style
attribute has the highest specificity.
- ID Selectors: Selectors containing an ID have a higher specificity than class selectors or tag selectors.
- Class and Attribute Selectors: Selectors with classes, attributes, and pseudo-classes contribute to specificity.
- Type (Tag) Selectors: Basic element selectors (e.g.,
div
, p
) have the lowest specificity.
Calculating Specificity
The specificity of a selector is typically represented as a four-part value, such as 0,0,0,0
, where each part corresponds to the specificity of inline styles, ID selectors, class/attribute selectors, and type selectors, respectively.
Share your thoughts in the comments
Please Login to comment...