Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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


Solution 2:

If you used .primary > a as the selector, then it would only match anchors that are immediate children of the class.

Of course then you couldn't do something like:

<div class="primary">
  <div class="wrapper">
    <a href="#">test</a>
  </div>
</div>

Solution 3:

Interesting question. In fact the second selector overrides the first one because they both have the same specificity value:.

In terms of value:
Inline Style > IDs > Classes > Attributes, and Pseudo-classes > Element Types and Pseudo-elements.

You can use a selector with higher specificity value to override the CSS declaration.

For instance:

div.secondary a { /* Specificity value = 12 */
    color: green;
}

Or:

.primary .secondary a {  /* Specificity value = 21 */
    color: green;
}

Here is an online tool to calculate the CSS Specificity.


Solution 4:

If you want the selector to respect the direct parent, you need to use the direct descendant selector >:

.primary > a {
    color: red;
}

Which translates to anchors only with a direct parent with class .primary


Solution 5:

Have a look at this great article about css selector specificity

Since your two rules are equivalent the one that comes last takes precidence. In order to prevent that you can make them more specific using the following:

div.secondary a {
    color: green;
}

-

.primary .secondary a {
    color:green;
}

etc


Post a Comment for "Css Precedence Based On Parent Div"