Quiz 1117: CSS Specificity
Explain CSS specificity and how it determines which styles are applied to elements.
Quick Answer
CSS specificity is a system used by browsers to determine which styles to apply to an element when multiple styles are defined. It prioritizes styles based on their origin and selector complexity, giving more weight to styles that are more specific to the element.
Explain in Depth
CSS specificity is a critical concept in understanding how CSS works. When multiple styles are defined for the same element, the browser needs to decide which one to apply. Specificity helps resolve these conflicts by assigning a weight to each CSS rule, with higher weights taking precedence.
Specificity Calculation:
Specificity is calculated using a four-part system, represented as a "point" system:
-
Inline Style: Styles directly applied to an element using the
style
attribute have the highest specificity, with a weight of1, 0, 0, 0
.<h1 style="color: red;">Heading</h1>
-
ID Selector: Styles with ID selectors (e.g.,
#my-id
) have a weight of0, 1, 0, 0
.#my-id { color: blue; }
-
Class, Attribute, and Pseudo-Class Selectors: Selectors like
.my-class
,[data-attribute]
and:hover
have a weight of0, 0, 1, 0
..my-class { font-weight: bold; }
-
Element Selector: Selectors targeting specific elements (e.g.,
h1
,p
) have a weight of0, 0, 0, 1
.h1 { text-align: center; }
Example:
Let's examine this code:
<!DOCTYPE html>
<html>
<head>
<title>CSS Specificity Example</title>
<style>
h1 {
color: blue; /* Specificity: 0, 0, 0, 1 */
}
#my-heading {
color: green; /* Specificity: 0, 1, 0, 0 */
}
.important {
color: red; /* Specificity: 0, 0, 1, 0 */
}
</style>
</head>
<body>
<h1 id="my-heading" class="important">This is a heading</h1>
</body>
</html>
In this example, the h1
element has three styles applied to it:
color: blue
(from the element selector)color: green
(from the ID selector)color: red
(from the class selector)
The browser will apply the style with the highest specificity, which is color: green
from the ID selector (#my-heading
).
Important Considerations:
- Specificity Inheritance: Specificity is inherited from parent elements.
- !important Rule: The
!important
declaration overrides all other styles, regardless of specificity. However, it is generally discouraged as it can make CSS difficult to maintain. - Specificity Calculator: Online tools and browser developer tools can help you calculate specificity and understand how styles are being applied.
Understanding CSS specificity is crucial for managing and troubleshooting CSS styles. By applying rules strategically and being aware of specificity weights, you can create a clean and predictable CSS architecture that works as expected.