LoginSignup
1
3

More than 5 years have passed since last update.

擬似クラス nth-childとnth-of-type

Last updated at Posted at 2017-10-20

擬似クラス nth-childとnth-of-typeの特徴と違い

擬似クラスであるnth-child等の挙動が分かりづらい。
また、nth-childとnth-of-typeの違いについて正確に記載されているものが少なかったので、投稿いたします。

特徴

まずは、nth-childで挙動を確認します。

  • 両者とも、親要素(1つ上)内の子要素(1つ下)が検索範囲であることを知っておく必要があります。

<ul class="list">
    <li class="item"><a class="link">1</a></li>
    <li class="item"><a class="link">2</a></li>
    <li class="item"><a class="link">3</a></li>
</ul>
.item:nth-child(even) { /* ulタグ内の偶数番目の要素がitemクラスか判定 */
    border-right: solid 1px #dcdcdc;
}

.link:nth-child(even) {     /* liタグ内の偶数番目の要素がitemクラスか判定 */
    border-bottom: solid 1px #dcdcdc;
}

昔は、クラスに適用できなかった説あり

nth-childとnth-of-typeの違い

それでは、本題に入ります。
ズバリ、検索範囲の中で、要素(p, a, liなど)を判別して数えるかどうかが違います。

  • item:nth-child(n) //n番目がitemクラスなら適用
  • item:nth-of-type(n) //要素ごとのn番目がitemクラスなら適用
.item:nth-child(1) {        
    border-bottom: blue;
}

.item:nth-of-type(1) {  
    color: red;
}
<div class="list">
    <a class="item">1</a>  //.item:nth-of-type(1)
    <p class="item"><a class="link">2</a></p> //.item:nth-child(1), .item:nth-of-type(1)
    <p class="item"><a class="link">3</a></p>
    <p class="item"><a class="link">4</a></p>
    <p class="item"><a class="link">5</a></p>
</div>

擬似クラスには、他にもfirst~~, last~~などありますが、上記の特徴を理解していれば問題ないかと思います。
かなり便利な使用方法は擬似クラスのカラムレイアウトでの便利な使用方法をご覧ください。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3