:first-of-typeと:first-child、:last-of-typeと:last-childの違い

:first-of-type:first-childの違いを理解できていなかったので、自分なりにまとめてみました。

もくじ

【結論】使いやすいのは:first-of-type

:first-of-type:first-childは1点を除き挙動をします。
異なる点は兄弟要素があるときの挙動です。

その1 :first-childで、兄弟要素が統一されているとき

例えば以下のコード。
:first-child:last-childで指示した通り文字の色が変わっています。
納得の挙動です。

<ul>
  <li>ホーム</li>
  <li>特徴</li>
  <li>料金</li>
  <li>お問い合わせ</li>
</ul>
li:first-child {
  color: red;
}

li:last-child {
  color: blue;
}

See the Pen Untitled by 伊とうito (@ito-the-typescripter) on CodePen.

その2 :first-childで、兄弟要素に異なる種類のタグがあるとき

続いてはこちら。
先程のコードをベースに、liタグの上下にpタグを追加してみました。

<ul>
  <p>追加</p>
  <li>ホーム</li>
  <li>特徴</li>
  <li>料金</li>
  <li>お問い合わせ</li>
  <p>追加</p>
</ul>
li:first-child {
  color: red;
}

li:last-child {
  color: blue;
}

See the Pen Untitled by 伊とうito (@ito-the-typescripter) on CodePen.

するとホームとお問い合わせの色は変わっていません
これはliタグの兄弟要素が追加され、最初と最後のliタグが無くなってしまった為です。

その3 :first-of-typeで、兄弟要素に異なる種類のタグがあるとき

その2と同じhtmlのコードに対して:first-of-typeを使用してみます。
すると、liタグの最初と最後の要素のみ色が変わっています。
恐らくこの挙動が一番素直で使いやすいと思います。

<ul>
  <p>追加</p>
  <li>ホーム</li>
  <li>特徴</li>
  <li>料金</li>
  <li>お問い合わせ</li>
  <p>追加</p>
</ul>
li:first-of-type {
  color: red;
}

li:last-of-type {
  color: blue;
}

See the Pen Untitled by 伊とうito (@ito-the-typescripter) on CodePen.

【まとめ】:first-of-typeと:last-of-typeがおすすめ

使用時の挙動を考えると:first-of-type:last-of-typeが使いやすいなと感じています。
迷ったら:first-of-typeと:last-of-typeで問題ないと思います!

もくじ