如何按类仅选择容器的第一个子元素?
我有复杂的 DIV 块相互连接,我无法编辑它们,因为此 html 代码是从系统提供的。我唯一能做的就是来自 CSS。
我只想选择“Child 1”。我的 CSS 确实选择了“Child 1”,但由于一些相关的类相互关联,它也选择了“Grand child 1”和“Great grandChild 1”,不幸的是!
请教我如何只选择“Child 1”。
谢谢!
.container > .child:first-child {
border: 1px solid red;
}
<div>
Parent
<div>
Child 1
</div>
<div>
Child 2
<div>
Child of Child 2
<div>
Grand Child 1
</div>
<div>
Grand Child 2
<div>
Parent
<div>
Great grandChild 1
</div>
<div>
Great grandChild 2
</div>
</div>
</div>
</div>
</div>
</div>
<div>
Parent
<div>
Child 1
</div>
<div>
Child 2
<div>
Child of Child 2
<div>
Grand Child 1
</div>
<div>
Grand Child 2
<div>
Parent
<div>
Great grandChild 1
</div>
<div>
Great grandChild 2
</div>
</div>
</div>
</div>
</div>
</div>
回答
这样只会选取.container不是孩子的.child。
:not(.child) > .container > .child:first-child {
border: 1px solid red;
}
- So far it's the only answer that matches OPs requirements generically enough to not tie it to the expectancy of a specific DOM structure *aside* of the code shown.