Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS precedence based on parent div

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

like image 499
Shaun Bowe Avatar asked Dec 20 '22 17:12

Shaun Bowe


1 Answers

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

like image 92
Zach Saucier Avatar answered Jan 09 '23 21:01

Zach Saucier