CSS Specificity
CSS specificity is a set of rules used to determine which CSS styles are applied to an element when multiple conflicting styles are specified. When multiple CSS rules target the same element and apply conflicting styles, specificity determines which style takes precedence. Specificity is calculated based on the selectors used to define the styles.
The following factors contribute to the specificity of a CSS rule:
- Inline Styles: Styles defined directly within the HTML element using the style attribute have the highest specificity. They are applied directly to the element and override any other styles.
- ID Selectors: Selectors that target elements by their unique ID have a higher specificity than other types of selectors. They are denoted by a hash symbol (#) followed by the ID name.
- Class Selectors, Attribute Selectors, and Pseudo-Classes: Selectors targeting elements by class, attribute, or pseudo-class have a medium level of specificity. They are represented by class names (prefixed with a dot .), attribute selectors, or pseudo-classes like :hover, :focus, etc.
- Type Selectors and Pseudo-Elements: Selectors targeting elements by their type (e.g., div, p, a) or pseudo-elements (e.g., ::before, ::after) have a lower specificity compared to the above selectors.
- Universal Selector and Combinators: Selectors like *, +, ~, and the combinators ( , >, +, ~) have the lowest specificity and are considered the least specific.
When comparing the specificity of two or more conflicting CSS rules, the following rules apply:
- The more specific selector takes precedence.
- If two selectors have the same specificity, the one that comes later in the CSS document or is defined later in an external stylesheet takes precedence (this is known as the "cascade" in Cascading Style Sheets).
For example, a style defined with an ID selector (#myElement) will override a style defined with a class selector (.myClass), and an inline style (<div style="color: red;">) will override both.