CSS控制层叠

8
我已经为用户构建了一个编辑器,其中有一组样式供选择。 以本例为例,我们将其称为.p1.p2。我的问题是,它们会根据它们在样式表中出现的顺序相互覆盖。我无法找到解决这个问题的方法,因为我不知道这些面板可能嵌套在哪里。 注:此示例大大简化,我无法精确控制像a标签这样的内容的位置,它们可以嵌套在表格、列表、段落或任何其他标记中,而且深度也不确定。 这也适用于标题和任何需要自定义样式(例如H1、ul...)以在显示环境中呈现良好的子元素。

.p1 a {
  color: red;
}
.p2 a {
  color: green;
}
<div class="pl p2">
  <a href="#">Hello 2</a>
  <div class="pl p1">
    <a href="#">Hello 2-1</a>
    <div class="pl p2">
      <a href="#">Hello 2-1-2</a>
    </div>
  </div>
</div>
<div class="pl p1">
  <a href="#">Hello 1</a>
  <div class="pl p2">
    <a href="#">Hello 1-2</a>
    <div class="pl p1">
      <a href="#">Hello 1-2-1</a>
    </div>
  </div>
</div>

我已经尝试使用:not选择器和在子元素上使用all:default,但都没有成功。

2个回答

3

看起来你可能需要使用直接子元素选择器>。在MDN上了解更多关于直接子元素选择器的信息

实时演示:

.p1 > a {
  color: red;
}
.p2 > a {
  color: green;
}
<div class="pl p2">
  <a href="#">Hello 2</a>
  <div class="pl p1">
    <a href="#">Hello 2-1</a>
    <div class="pl p2">
      <a href="#">Hello 2-1-2</a>
    </div>
  </div>
</div>
<div class="pl p1">
  <a href="#">Hello 1</a>
  <div class="pl p2">
    <a href="#">Hello 1-2</a>
    <div class="pl p1">
      <a href="#">Hello 1-2-1</a>
    </div>
  </div>
</div>


很遗憾,我无法控制那个a标签的位置,它可能在列表、表格、段落中,或者嵌套在完全不同的东西中。 - Chris Seufert
@cseufert 如果您不想使用上述解决方案,那么您可以将类.forP1.forP2添加到<a>中。这样,您就可以编写p1 .forP1 {...}p2 .forP2 {...}。这是您可以做的。 - Junaid

2
你的示例有点混乱,因为同一个元素应用了两个类。
如果我理解正确,你想让 a 元素由 DOM 中最近的祖先元素进行样式设置。
如果是这样,解决方案就是设置一组规则,其中具有这两个类之一的祖先将始终匹配,因此具有最高特异性的规则将获胜...
抱歉,我找不到更好的解释方式...

.p1 a, 
*[class^=p] .p1 a, 
*[class^=p] *[class^=p] .p1 a, 
*[class^=p] *[class^=p] *[class^=p] .p1 a 
{
 background-color: antiquewhite;
}

.p2 a, 
*[class^=p] .p2 a, 
*[class^=p] *[class^=p] .p2 a, 
*[class^=p] *[class^=p] *[class^=p] .p2 a 
{
 background-color: lightblue;
}
<div class="p2">
  <a href="#">Hello 2</a>
  <div class="p1">
    <a href="#">Hello 2-1</a>
    <div class="p2">
      <a href="#">Hello 2-1-2</a>
    </div>
  </div>
</div>
<div class="p1">
  <a href="#">Hello 1</a>
  <div class="p2">
    <a href="#">Hello 1-2</a>
    <div class="p1">
      <a href="#">Hello 1-2-1</a>
    </div>
  </div>
</div>


是的,这与我之前的想法相似。 - Chris Seufert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接