如何使HTML标签为父母的顺序应用具有相同特异性的css选择器?

Fin*_*sse 6 html css css-selectors css-specificity

有许多相同级别的CSS样式和带有嵌套块的HTML代码,应用了样式:

.style1 a {
  color: red;
}
.style2 a {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

结果,第二个链接("Style 1")变为绿色.之所以会发生这种情况,是因为链接标记对两个CSS选择器具有相同的特异性,并且.style2 a稍后会声明,因此.style2 a适用

如何从最近的样式类父项中应用样式,而没有关于标记嵌套的初步信息(使第二个链接变为红色)?

代码游乐场:http://codepen.io/anon/pen/zvXmOw

HTML可以修改.但请考虑链接可能在任何地方.

----------

我发现的最佳解决方案基于极限嵌套.首先(与样式父级的链接标记距离有限):

.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

第二个(style-divs嵌套有限):

.style1 a,
.style .style1 a,
.style .style .style1 a {
  color: red;
}
.style2 a,
.style .style2 a,
.style .style .style2 a {
  color: green;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

我试图找出没有限制的更好的解决方案.

Fin*_*sse 2

可以使用CSS 变量来实现:

a {
  color: var(--link-color);
}
.style1 {
  --link-color: red;
}
.style2 {
  --link-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

这项技术已经得到了浏览器的广泛支持,并且将来还会得到更广泛的支持。