我试图理解为什么下面的示例没有按预期运行。我有一个选择一般 sibling 的风格,但我也有我不希望被选中但偶尔会被选中的 child 。这是说明问题的最小示例。
第一个 div>div.h
是后代,~
不匹配它。第二个 p>div.h
显然是后代,但 ~
选择器确实匹配它。我在 Chrome、Safari 和 Firefox 中试过,它们的行为都一样。我肯定错过了什么。 p
“特别”吗?
<html>
<head>
<style>
.anchor ~ .h { color: orange }
.anchor2 ~ .h { color: blue }
</style>
</head>
<body>
<div>
<div class="h">black 1</div>
<div class="h">black 2</div>
<p class="anchor">the anchor</p>
<div class="h">orange 1</div>
<div>
<div class="h">should be black</div>
</div>
<p>
<div class="h">why isn't this black</div>
</p>
<div class="h">orange 2</div>
<p class="anchor2">anchor2</p>
<div class="h">blue 1</div>
<div class="h">blue 2</div>
</div>
</body>
</html>
最佳答案
<div>
elements are not valid children of <p>
.
您的浏览器会更正您的错误(获取您的 <div>
并将其放在 <p>
之后,而不是放在里面),并通过这样做,生成 div.h
.anchor
的 sibling :
现在,如果您在段落中使用内联元素,浏览器不会更正您的标记,您会得到预期的结果:
.anchor ~ .h {
color: orange
}
.anchor2 ~ .h {
color: blue
}
<div>
<div class="h">black 1</div>
<div class="h">black 2</div>
<p class="anchor">the anchor</p>
<div class="h">orange 1</div>
<div>
<span class="h">should be black</span>
</div>
<p>
<span class="h">why isn't this black</span>
</p>
<div class="h">orange 2</div>
<p class="anchor2">anchor2</p>
<div class="h">blue 1</div>
<div class="h">blue 2</div>
</div>
关于CSS通用兄弟组合器(即~),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049233/