CSS同时使用contains和第一个子选择器[duplicate]

yqhsw0fo  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(195)
    • 此问题在此处已有答案**:

(23个答案)
Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?(8个答案)
3天前关闭。
我试着在css中使用contains选择器和第一个子选择器,但是不能让它工作。没有: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>

我试着同时使用两个选择器,我试着使用第一个子选择器而不使用包含选择器,它起作用了,我也试着使用包含选择器而不使用第一个子选择器,它起作用了,但是一起使用它们就不行了。

smtd7mpg

smtd7mpg1#

它确实有效。
它所做的并不是你所期望的。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伪选择器的东西,尽管this answer解释了为什么它也可能不像您所期望的那样使用其他参数。

bvjveswy

bvjveswy2#

你需要两条规则。
第一个目标是要修改的元素。
第二种方法保持以下元素不变。

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>

相关问题