CSS specificity refers to the set of rules that determine which CSS styles should be applied to an element when multiple conflicting styles are present. It is important because it helps to resolve conflicts and ensure that the correct styles are applied consistently across a webpage.
CSS specificity is calculated based on the combination of selectors used to target an element. Each selector has a specific weight assigned to it, and the styles with higher specificity will override those with lower specificity.
The specificity hierarchy is as follows:
- Inline styles: Styles applied directly to an element using the
style
attribute have the highest specificity. They are defined within the HTML tag itself and take precedence over all other styles. - ID selectors: Styles applied using the
id
attribute have a higher specificity than class selectors. An ID selector is denoted by a hash symbol (#) followed by the ID name. - Class selectors: Styles applied using class selectors have a lower specificity than ID selectors. A class selector is denoted by a period (.) followed by the class name.
- Element selectors: Styles applied using element selectors have the lowest specificity. An element selector targets all elements of a specific type, such as
<div>
or<p>
.
When multiple styles with different specificity levels conflict, the style with the highest specificity will be applied. If two styles have the same specificity, the one that appears later in the CSS file will take precedence.
To demonstrate CSS specificity in JavaScript and HTML, consider the following example:
<!DOCTYPE html> <html> <head> <style> /* Specificity: 0, 0, 1 */ p { color: blue; } /* Specificity: 0, 1, 0 */ .my-class { color: red; } /* Specificity: 1, 0, 0 */ #my-id { color: green; } </style> </head> <body> <p class="my-class" id="my-id">Hello, CSS specificity!</p> </body> </html>
In this example, the paragraph element has a class of “my-class” and an ID of “my-id”. The CSS styles applied to it have different specificity levels. The color of the text will be green because the ID selector has the highest specificity. If we remove the ID selector, the color will be red because the class selector has the next highest specificity. Finally, if we remove both the ID and class selectors, the color will be blue because the element selector has the lowest specificity.
Understanding CSS specificity is crucial for writing maintainable and predictable CSS code. It helps to avoid unexpected style conflicts and ensures that styles are applied consistently based on their intended hierarchy.