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

How to make css selectors with the same specificity be applied in order of HTML tags parenthood?

有一堆 same-level CSS 样式和一个 HTML 带有应用样式的嵌套块的代码:

.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>

因此,第二个 link(«样式 1»)变为绿色。发生这种情况是因为 link 标记对 CSS 选择器具有相同的特异性,并且 .style2 a 稍后声明,因此应用 .style2 a

如何在没有有关标签嵌套的初步信息的情况下从最近的 style-class parent 应用样式(使第二个 link 为红色)?

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

HTML可以修改。但是请考虑 links 可能在任何地方。

————————————

我发现的最佳解决方案是基于限制嵌套。首先(link 到 style-parent 的标签距离有限):

.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>

其次(style-divs嵌套受限):

.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>

我想知道是否有更好的无限制解决方案。

How to make css selectors with the same specificity be applied in order of HTML tags parenthood?

你不能。 CSS 根本不是那样的。如果选择器具有相同的特异性,则规则将按样式表顺序应用。你无法改变这一点。

您可以通过在链接上 color: inherit 并在属于 类.

的成员的元素上设置颜色来实现您想要的效果

直接在锚点上设置 类 可能会更容易。

这是定义的问题。最好制作一个 link .green 来制作一个带有 .green 类名的 div 来应用他的孩子。良好的 CSS 实践表明最好这样做:

 <a href="" class="green">Green link</a>
 <a href="" class="red">Red link</a>

他们在哪里并不重要。如果特定样式适合 links,为什么不为它们编写一个好的代码?

最好的办法可能是像这样删除跨度和 div:

<div class="style2">
    <a href="/">Style 2</a>
    <div class="style1">
        <a href="/">Style 1</a>
    <div class="style2">
        <a href="/">Style 2</a>
    </div>
</div>

然后使用这个 CSS:

.style1 > a {
    color: red;
}
.style2 > a {
    color: green;
}

Fiddle: http://jsfiddle.net/09c6x5pp/

编辑:

如果你想保持跨度和div:

.style1 > a,
.style1 > div > a {
    color: red;
}
.style2 > a,
.style2 > span > a {
    color: green;
}

可以使用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>

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