Search code examples
htmlcsscss-selectorshtml-listspseudo-class

Why First-of-type in ul list is not working


Code

ul a:first-of-type {
  color: red;
}
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li><a href="#">Item 3</a>
  </li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
  <li>Item 10</li>
  <li>Item 11</li>
  <li><a href="#">Item 12</a>
  </li>
  <li>Item 13</li>
  <li>Item 14</li>
  <li>Item 15</li>
  <li>Item 16</li>
</ul>

Result Fiddle

Why is the a item 12 selected? It is not the first sibling of its type, it is the last.


Solution

  • :first-of-type refers to the type so because a is child of the li and as you can see there is no more a elements as siblings within those li so it will select every first-of-type of a within the li

    take a look at this snippet with a li with 2 a being child of li it will select only the first a:

    Snippet

    ul a:first-of-type {
      color: red;
    }
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li><a href="#">Item 3a</a>
        <a href="#">Item 3b</a>
      </li>
      <li>Item 4</li>
      <li>Item 5</li>
      <li>Item 6</li>
      <li>Item 7</li>
      <li>Item 8</li>
      <li>Item 9</li>
      <li>Item 10</li>
      <li>Item 11</li>
      <li><a href="#">Item 12</a>
      </li>
      <li>Item 13</li>
      <li>Item 14</li>
      <li>Item 15</li>
      <li>Item 16</li>
    </ul>

    If you want target only the item 3, you can use nth-of-type on li, like this:

    Snippet

    ul li:nth-of-type(3) a {
      color: red;
    }
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li><a href="#">Item 3</a>
      </li>
      <li>Item 4</li>
      <li>Item 5</li>
      <li>Item 6</li>
      <li>Item 7</li>
      <li>Item 8</li>
      <li>Item 9</li>
      <li>Item 10</li>
      <li>Item 11</li>
      <li><a href="#">Item 12</a>
      </li>
      <li>Item 13</li>
      <li>Item 14</li>
      <li>Item 15</li>
      <li>Item 16</li>
    </ul>