If you view the following code in a browser the link appears red. I would expect it to be green because the secondary div is nested inside the primary div. It appears the color is determined by the order of the elements in the css file. If I move .secondary after .primary the link is green.
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
.secondary a {
color: green;
}
.primary a {
color: red;
}
</style>
</head>
<body>
<div class="primary">
<div class="secondary">
<a href="http://www.google.com">test</a>
</div>
</div>
</body>
</html>
Other than changing the order in the file how can I make the link respect the color from its parent div?
EDIT: This is a very simplified example. In practice there could be many other div tags between the primary and secondary classes.
Link to codepen
The issue is that the two selector have the same specificity. The only thing that CSS knows to do with selectors of the same specificity is to choose the most recent one
Thus, you need to make the specificity of the child more than the firsts, one way is to put
.primary .secondary a {
color:green;
}
Another way would be to put the element type in addition to the class
This is the reason why it is proper formatting to structure your CSS as the page it is laid out in the HTML, with parents coming before children
For more information as to how specificity is determined, check here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With