Home >Web Front-end >CSS Tutorial >CSS Specificity Explained: How to Control Which Styles Win
Have you ever spent hours tweaking your CSS, wondering why that one stubborn style won’t apply? Welcome to the world of specificity.
Specificity is how browsers decide which CSS rule to apply when multiple rules target the same element. Without understanding it, your stylesheets can quickly turn into a tangled mess. Let’s break it down.
The universal selector (*) is at the bottom of the specificity chain with 0 points. It’s like a blanket rule for everything but gets overridden by nearly anything else.
Example:
* { color: red; } h1 { color: blue; }
Even with * { color: red; }, an
Element selectors (h1, p, div) are stronger than universal selectors, carrying 1 point.
Example:
h1 { color: green; }
This rule will override a universal selector targeting the same element.
Selectors like .button, :hover, or [type="text"] are more specific, with 10 points.
Example:
.button { color: purple; }
This will override both universal and element selectors.
IDs (#submitButton) are significantly more powerful, with 100 points. Use them sparingly, as they can make styles harder to manage.
Example:
#submitButton { background-color: yellow; }
Inline styles trump everything except !important.
Example:
<div> <h4> 6. The Almighty !important </h4> <p>Adding !important forces a rule to override others, even inline styles. But overusing it can lead to chaos in your CSS. It can be necessary when using third-party libraries to help override predefined styles.</p> <p><strong>Example:</strong><br> </p> <pre class="brush:php;toolbar:false">.button { color: red !important; }
If two rules have the same specificity, the one that comes later in the stylesheet wins.
Example:
h1 { color: red; } h1 { color: green; }
Here,
Mastering specificity lets you write clean, maintainable CSS, saving you from endless debugging. The next time your styles don’t behave, you’ll know exactly where to look.
The above is the detailed content of CSS Specificity Explained: How to Control Which Styles Win. For more information, please follow other related articles on the PHP Chinese website!