CSS interview question

What is the difference between the “nth-child()” and “nth-of-type()” selectors?

Answer

The nth-child() pseudo-class is used to match an element based on a number, which represents the element's position amongst it's siblings. More specifically, the number represents the number of siblings that exist before the element in the document tree (minus 1).

Example:

.example :nth-child(4) { background: #ffdb3a; }
<div class="example">
  <p>This is a <em>paragraph</em>.</p>
  <p>This is a <em>paragraph</em>.</p>
  <p>This is a <em>paragraph</em>.</p>
  <div>This is a <em>divider</em>.</div> <!-- Element to select -->
  <div>This is a <em>divider</em>.</div> 
</div>

The nth-of-type() pseudo-class, like nth-child(), is used to match an element based on a number. This number, however, represents the element's position within only those of its siblings that are of the same element type.

This number can also be expressed as a function, or using the keywords even or odd.

.example p:nth-of-type(odd) { background: #ffdb3a; }
<div class="example">
  <p>This is a <em>paragraph</em>.</p> <!-- Element to select -->
  <p>This is a <em>paragraph</em>.</p>
  <p>This is a <em>paragraph</em>.</p> <!-- Element to select -->
  <div>This is a <em>divider</em>.</div>
  <div>This is a <em>divider</em>.</div> <!-- Element to select -->
</div>

More Technical Interview Topics