仅使用CSS如何选择第二级锂

时间:2019-05-10 00:24:12

标签: css

我需要选择第二级li并将颜色更改为红色,然后自行选择第三级li并设置为蓝色。有帮助吗?

    <title>Warehouse</title>
    <style>
      /* Write your CSS solution here */
      ul:nth-of-type(1):first-child{
          font-weight: bold;
      }
      ul:nth-of-type(1) > ul:nth-of-type(1):first-child{
          font-style: italic;
      }

    </style>
  </head>
  <body>
    <ul>
      <li>first level
        <ul>
          <li>second level
            <ul>
              <li>third level</li>
              <li>third level</li>
            </ul>
          </li>
        </ul>
        <ul>
          <li>4th level
            <ul>
              <li>5th level</li>
              <li>5th level</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </body>
</html>

我希望这会选择第二级li,但它没有

2 个答案:

答案 0 :(得分:1)

您可以利用 child combinator > 专门针对具有li > ul > lili > ul > li > ul > li的子孙:

ul:nth-of-type(1):first-child {
  font-weight: bold;
}

ul:nth-of-type(1)>ul:nth-of-type(1):first-child {
  font-style: italic;
}

li > ul > li {
  color: red;
}

li > ul > li > ul > li {
  color: blue;
}
<body>
  <ul>
    <li>first level
      <ul>
        <li>second level
          <ul>
            <li>third level</li>
            <li>third level</li>
          </ul>
        </li>
      </ul>
      <ul>
        <li>4th level
          <ul>
            <li>5th level</li>
            <li>5th level</li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</body>

即使孙子代最初会上色red,但由于 specificity 的增加,他们的颜色仍会覆盖blue

如果按“级别”表示文本表示形式而不是DOM层次结构,则可以将:first-of-type伪类和:nth-of-type(2)链接起来以“重新”应用孙辈的默认 >使用选择器black的颜色li > ul:nth-of-type(2) > li > ul > li

ul:nth-of-type(1):first-child {
  font-weight: bold;
}

ul:nth-of-type(1) > ul:nth-of-type(1):first-child {
  font-style: italic;
}

li > ul:first-of-type > li {
  color: red;
}

li > ul:first-of-type > li > ul > li {
  color: blue;
}

li > ul:nth-of-type(2) > li > ul > li {
  color: black;
}
<body>
  <ul>
    <li>first level
      <ul>
        <li>second level
          <ul>
            <li>third level</li>
            <li>third level</li>
          </ul>
        </li>
      </ul>
      <ul>
        <li>4th level
          <ul>
            <li>5th level</li>
            <li>5th level</li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</body>

同样,这与将选择器设置为red的选择器相比,具有更高的特异性:

enter image description here

答案 1 :(得分:0)

您忘记了>选择了直子

使用子组合器,它必须看起来像这样:

ul:nth-of-type(1) > li > ul:nth-of-type(1):first-child {}

但是您可以将大多数时间简化为

ul:nth-of-type(1) ul:nth-of-type(1):first-child {}

但是在两种情况下都要当心,当增加树的深度时...这些选择器将在所有级别上找到所有“对”;)

我建议您进一步阅读MDN文档:
https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

相关问题