将第一个孩子限制为仅第一个孩子而没有后代

时间:2018-10-10 12:30:09

标签: html css

在以下代码段中,我只想要图例后的第一个div,该文本包含文本one,除了选择three之外,也没有其他内容

.container fieldset div:first-of-type {
  border: 1px solid red;
}
<html>

  <body>
    <div class="container">
      <fieldset>
      <legen>blah</legen>
        <div>one</div>
        <div>two
          <div>three</div>
        </div>
        <div>three</div>
      </fieldset>
    </div>
  </body>

</html>

1 个答案:

答案 0 :(得分:4)

您的意思是您只想选择div为“ two”的div而不是“ three”的div,对吗?

然后使用直接后代选择器>

.container fieldset > div:first-of-type {
  border: 1px solid red;
}
<html>

  <body>
    <div class="container">
      <fieldset>
      <legen>blah</legen>
        <div>one</div>
        <div>two
          <div>three</div>
        </div>
        <div>three</div>
      </fieldset>
    </div>
  </body>

</html>

.container fieldset div:first-of-type {
  border: 1px solid red;
}
<html>

  <body>
    <div class="container">
      <fieldset>
      <legen>blah</legen>
        <div>one</div>
        <div>two
          <div>three</div>
        </div>
        <div>three</div>
      </fieldset>
    </div>
  </body>

</html>