我需要在CSS中选择第n级元素
下面是一个示例代码
div>div>p {
background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Heading</h1>
<div>
<h2>Random sibling</h2>
<p>First Level child.</p>
<div>
<h2>Random sibling</h2>
<p>Second Level child.</p>
<div>
<h2>Random sibling</h2>
<p>Third Level child.</p>
</div>
</div>
</div>
<div>
<span><p>Descendent child.</p></span>
</div>
<p>Not a child.</p>
</body>
</html>
我只想选择二级孩子并防止三级孩子被设计
我们如何做到这一点?
我不确定你为什么不使用任何类或id,但在你的Css代码上尝试这个
div>div>p:not(:last-child) {
background-color: yellow;
}
div>div>p:not(:last-child) {
background-color: yellow;
}
<h1>Heading</h1>
<div>
<h2>Random sibling</h2>
<p>First Level child.</p>
<div>
<h2>Random sibling</h2>
<p>Second Level child.</p>
<div>
<h2>Random sibling</h2>
<p>Third Level child.</p>
</div>
</div>
</div>
<div>
<span><p>Descendent child.</p></span>
</div>
<p>Not a child.</p>
您可能需要向第一个<div>
元素添加标识符,然后通过parent>子子选择器遍历子树,如下所示:
.main > div:first-of-type > p {
background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Heading</h1>
<div class='main'>
<h2>Random sibling</h2>
<p>First Level child.</p>
<div>
<h2>Random sibling</h2>
<p>Second Level child.</p>
<div>
<h2>Random sibling</h2>
<p>Third Level child.</p>
</div>
</div>
</div>
<div>
<span><p>Descendent child.</p></span>
</div>
<p>Not a child.</p>
</body>
</html>