There are many CSS styles at the same level and HTML code with nested blocks that apply styles:
.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") turns green. This is because the link tag has the same specificity for both CSS selectors, and .style2 a declared later, so .style2 a is applied.
How to make a style be applied from the nearest parent of a style class without preliminary information on nesting tags (so that the second link is red)?
Playground Code: http://codepen.io/anon/pen/zvXmOw
HTML is subject to change . But keep in mind that links can be anywhere.
----------
The best solutions I've found are based on the utmost investment. The first (the link tagโs 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 (nesting style of divs 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 if there is a better solution without limits.
source share