When multiple style declarations conflict on an element, the CSS Cascade plays a vital role in determining which CSS rules will be applied to that element.
One crucial aspect that the Cascade considers is known as Specificity.
Understanding Specificity:
A more specific CSS declaration always takes precedence over less specific ones, regardless of where it appears in the stylesheet.
In general,
- An ID selector (
#id
) holds higher specificity than any number of class selectors (.class
), and a class selector has higher specificity than any number of type selectors (e.g. h1
).
- If no declaration contains a selector with higher specificity, a larger amount of a single selector will override a smaller amount of the same selector (as seen in your situation).
It's important to note that .news a
is more specific because it includes both a class selector and a type selector, making it preferred over .news-links
which only has one class selector.
In the code snippet below, I added another type selector with .news-links
to make it equally specific, ensuring that this style will now be applied since it appears later in the stylesheet (based on Rule Order).
To delve deeper into Specificity, you can refer to MDN.
.news a {
text-decoration: underline;
}
li .news_links {
text-decoration: none;
}
.news_links:hover {
text-decoration: underline;
}
<div class="news">
<h2>Lorem ipsum</h2>
<p>At vero eos et accusam et justo duo dolores et ea rebum.</p>
<p><a href="xxx" target="blank">Individual Link</a></p>
<!-- **underline** -->
<ol>
<li><a class="news_links" href="xxx" target="blank">List Link</a></li>
<!-- **no-underline, but underline-hover** -->
</ol>
</div>