When more than one set of CSS rules applies to the same element, the browser will have to decide which
specific set will be applied to the element.
- Inline Styles
- ID Selectors
- Class Selectors
- Element and Pseudo-element Selectors
- Inline Styles:
Styles applied directly to an element using the style attribute within the HTML. Inline
styles have the highest specificity and override all other rules.
Example:
<p style="color: red;">This text is red.</p>
Output:
This text is red.
- ID Selectors:
Selectors that target elements by their id attribute. They are more specific than classes or element
selectors.
Example:
<html>
<head>
<style>
#my-element
{
color:green;
}
</style>
</head>
<body>
<p id="my-element">This text is green. </p>
<body>
<html>
Output:
This text is green.
- Class Selectors:
Selectors targeting elements by their class or attribute. These selectors have a moderate level of
specificity.
Example:
<html>
<head>
<style>
.my-class
{
color: blue;
}
</style>
</head>
<body>
<p class=”my-class>Color is blue</p>
</body>
</html>
Output:
Color is blue
- Element and Pseudo-element Selectors:
Selectors targeting elements by their tag name or pseudo-elements like: before and: after. They have the
lowest specificity and are easily overridden by more specific selectors.:
Example:
<html>
<head>
<style>
span
{
color: pink;
}
</style>
</head>
<body>
<span>Color is pink</span>
</body>
</html>
Output:
Color is pink
Here's how specificity works:
- Specificity is calculated as a four-part value, such as "a, b, c, d," where "a" represents inline styles, "b" represents IDs, "c" represents classes, attributes, and pseudo-classes, and "d" represents element and pseudo-element selectors.
- The selector with the highest specificity is chosen, and its styles are applied.
- If multiple selectors have the same specificity, the one defined later in the stylesheet or in the HTML takes precedence.