如何在CSS中选择第n级元素

时间:2018-03-02 17:26:00

标签: css css-selectors

我需要在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>

我只想选择二级孩子并防止三级孩子被设置样式

我们如何做到这一点?

2 个答案:

答案 0 :(得分:3)

您可能需要向第一个<div>元素添加标识符,然后按父级&gt;遍历子树。儿童选择器如下:

.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>

答案 1 :(得分:3)

我不确定为什么不使用任何课程或ID,但请在您的Css代码上试用

div>div>p:not(:last-child) {
  background-color: yellow;
}

&#13;
&#13;
div>div>p:not(:last-child) {
  background-color: yellow;
}
&#13;
<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>
&#13;
&#13;
&#13;