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.