nth-of-type、first-of-type、last-of-type的理解

116 阅读1分钟

nth-of-type、first-of-type、last-of-type的理解

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
      ul .ll:nth-of-type(n) {
        color: red;
      }

      /*ul下的所有带ll样式的元素,然后根据元素的标签名分类,再匹配分类后的最后一个*/
      ul .ll:last-of-type {
        color: greenyellow;
      }

      ul .ll:first-of-type {
        color: gold;
      }
    </style>
  </head>
  <body>
    <ul id="ul4">
      <li>这是第1个li</li>
      <h1 class="ll">h1中的first,且有ll样式</h1>
      <li class="ll">不是li中的first,但有ll样式</li>
      <li>这是第3个li</li>
      <li></li>
      <li>这是第5个li</li>
      <li class="ll"><span>这是第6个li</span><span>这是第6个li</span></li>
      <li>这是第7个li</li>
      <li class="ll">li中的last,且有ll样式</li>
      <h1>这是一个h1</h1>
      <h1 class="ll">h1中的last,且有ll样式</h1>
    </ul>
  </body>
</html>

图片.png

E:first-child

E:last-child: 先匹配所有兄弟元素中的最后一个,再看是否命中:last-child前面的条件

E:first-of-type

E:last-of-type:先根据选择器去找标签,将匹配的标签以名称进行分组,再判断是否是同名标签最后的位置。