There are a bunch of same-level CSS styles and an HTML code with nested blocks to which the styles are applied:
.style1 a {
color: red;
}
.style2 a {
color: green;
}
<div class="style2">
<span>
<a href="/">Style 2</a>
</span>
<div class="style1">
<div>
<a href="/">Style 1</a>
</div>
<div class="style2">
<a href="/">Style 2</a>
</div>
</div>
</div>
As a result the second link («Style 1») becomes green. It happens because the link tag has the same specificity for both CSS selectors and .style2 a
is declared later, so .style2 a
is applied.
How to make the style be applied from the nearest style-class parent without preliminary information about the tags nesting (to make the second link be red)?
Code playground: http://codepen.io/anon/pen/zvXmOw
The HTML is able to be modified. But consider that links may be anywhere.
——————————
The best solutions I've found are based on limit nesting. First (link tag distance from style-parent is limited):
.style1 > a,
.style1 > :not(.style) > a,
.style1 > :not(.style) > :not(.style) > a {
color: red;
}
.style2 > a,
.style2 > :not(.style) > a,
.style2 > :not(.style) > :not(.style) > a {
color: green;
}
<div class="style style2">
<span>
<a href="/">Style 2</a>
</span>
<div class="style style1">
<div>
<a href="/">Style 1</a>
</div>
<div class="style style2">
<a href="/">Style 2</a>
</div>
</div>
</div>
Second (style-divs nesting is limited):
.style1 a,
.style .style1 a,
.style .style .style1 a {
color: red;
}
.style2 a,
.style .style2 a,
.style .style .style2 a {
color: green;
}
<div class="style style2">
<span>
<a href="/">Style 2</a>
</span>
<div class="style style1">
<div>
<a href="/">Style 1</a>
</div>
<div class="style style2">
<a href="/">Style 2</a>
</div>
</div>
</div>
I am trying to find out is there a better solution without limits.
How to make css selectors with the same specificity be applied in order of HTML tags parenthood?
You can't. CSS simply doesn't work like that. If selectors have equal specificity then rules are applied in stylesheet order. You can't change that.
You might be able to achieve the effect you want with color: inherit
on the links and setting the colours on the elements that are members of the classes.
It would probably be easier to set the classes on the anchors directly.
It can be achieved using CSS variables:
a {
color: var(--link-color);
}
.style1 {
--link-color: red;
}
.style2 {
--link-color: green;
}
<div class="style2">
<span>
<a href="/">Style 2</a>
</span>
<div class="style1">
<div>
<a href="/">Style 1</a>
</div>
<div class="style2">
<a href="/">Style 2</a>
</div>
</div>
</div>
This technology is supported by browsers widely already, and will get even wider support in future.
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