Selector - :nth-child()與:nth-of-type()的差別

 

:nth-child()與:nth-of-type()的差別

<!DOCTYPE html>
<html>

<head>
  <style>
    .first>p:nth-of-type(2) {
      background: red;
    }

    .second>p:nth-child(2) {
      background: blue;
    }

    .three>:nth-of-type(odd) {
      background: yellow;
    }

    .four>:nth-child(even) {
      background: green;
    }

    .five>p:nth-child(3n+2) {
      background: pink;
    }
  </style>
</head>

<body>
  <div class="first">
    <p>The first paragraph.</p>
    <h1>The second paragraph.</h1>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>
  </div>
  <br>
  <div class="second">
    <p>The first paragraph.</p>
    <h1>The second paragraph.</h1>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>
  </div>
  <br>
  <div class="three">
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
  </div>
  <br>
  <div class="four">
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
  </div>
  <br>
  <div class="five">
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p>
    <p>7</p>
    <p>8</p>
    <p>9</p>
    <p>10</p>
  </div>

</body>

</html>

說明:

:nth-of-type() selector 是指將上一階所篩選的元素中,選出第 n 個元素;

而 :nth-chlid() selector 則會更嚴格,是指將上一階所篩選的元素中,

從父元素看進來,其子元素的順序一定要排在第 n 個才會被選到。