CSS同时使用contains和first-child选择器



我试图在css和第一个子选择器一起使用包含选择器,不能让它工作。它的工作没有:first-child选择器,这让我认为也许只是不可能?在下面的例子中,我只希望第一个id为taco的p的背景色为黄色。

<!DOCTYPE html>
<html>
<head>
<style>
p[id*="taco"]:first-child {
background-color: yellow;
}
</style>
</head>
<body>
<p>This paragraph is the first child of its parent (body).</p>
<p>This paragraph is not the first child of its parent (body).</p>
<p>This paragraph is the first child of its parent (div).</p>
<p>This paragraph is not the first child of its parent (div).</p>
<p id="taco">This paragraph is the first child of its parent (body).</p>
<p id="taco">This paragraph is not the first child of its parent (body).</p>
<p id="taco">This paragraph is the first child of its parent (div).</p>
<p id="taco">This paragraph is not the first child of its parent (div).</p>

</body>
</html>

我尝试使用两个选择器。我尝试使用第一个孩子没有包含选择器,它工作了。我还尝试使用包含选择器没有第一个子选择器,这是有效的,但使用它们在一起不。

它确实有效。

它所做的不是你所期望的。CSS正在查找同时为:first-child[id*="taco"]的元素

id中没有包含taco的第一个子节点。

<p>This paragraph is the first child of its parent (body).</p>

id中不包含taco

不知道你到底想做什么,但我猜你宁愿得到具有特定id的第一个元素而不是:first-child。然而,Id应该保持唯一,所以我建议使用类来代替。

因此,您寻找类似:first-of-type的伪选择器,尽管这个答案解释了为什么它也可能不像您期望的那样与其他参数一起工作。我希望这确实能帮助你找到解决你主要问题的办法。

你需要两条规则。

第一个以要修改的元素为目标。

第二个命令保持以下元素不变。

p.taco {
background-color: yellow;
}
p.taco ~ p {
background-color: white;
}
<p>This paragraph is the first child of its parent (body).</p>
<p>This paragraph is not the first child of its parent (body).</p>
<p>This paragraph is the first child of its parent (div).</p>
<p>This paragraph is not the first child of its parent (div).</p>
<p class="taco">This paragraph is the first child of its parent (body).</p>
<p class="taco">This paragraph is not the first child of its parent (body).</p>
<p class="taco">This paragraph is the first child of its parent (div).</p>
<p class="taco">This paragraph is not the first child of its parent (div).</p>

最新更新