LoginSignup
2
3

More than 3 years have passed since last update.

[自分用メモ]擬似クラス違い first-child/last-child/first-of-type/last-of-type

Last updated at Posted at 2019-10-06

擬似クラス[first-child][last-child]が効かない原因が、
それぞれの使い方を少し勘違いしていたことだったのでメモ。

dl要素のテーブルで考える

スクリーンショット 2019-10-06 17.31.50.png

<dl>
  <dt>dt (first-of-typeで指定可能) or (first-childで指定可能)</dt>
  <dd>dd (first-of-typeで指定可能)</dd>
  <dt>dt</dt>
  <dd>dd</dd>
  <dt>dt (last-of-typeで指定可能)</dt>
  <dd>dd (last-of-typeで指定可能) or (last-childで指定可能)</dd>
</dl>

:first-child

親要素に対するすべての子要素の中で、最初の子要素のみに適用される。

dl要素のテーブルで考えると、最初の子要素はdtなので

▼OK

dt:first-child {
}

▼NG

dd:first-child {
}

:last-child

親要素に対するすべての子要素の中で、最後の子要素のみに適用される。

dl要素のテーブルで考えると、最後の子要素はddなので

▼OK

dd:last-child {
}

▼NG

dt:last-child {
}

「dtの中で最後」 or 「ddの中で最後」の要素を指定したい場合は、以下の擬似クラスを使えば良い!

:first-of-type

特定の子要素の中で、最初の子要素のみに適用される。

dl要素のテーブルで考えると、 dtとdd共に使える。

▼OK

dt:first-of-type {
}

つまり、dt:first-of-typeは、「数あるdt要素の中でも最初のdt要素のみ」に適用される。

dd:first-of-type {
}

つまり、dd:first-of-typeは、「数あるdd要素の中でも最初のdd要素のみ」に適用される。

:last-of-type

特定の子要素の中で、最後の子要素のみに適用される。

dl要素のテーブルで考えると、 dtとdd共に使える。

▼OK

dt:last-of-type {
}

つまり、dt:las-of-typeは、「数あるdt要素の中でも最後のdt要素のみ」に適用される。

dd:last-of-type {
}

つまり、dd:last-of-typeは、「数あるdd要素の中でも最後のdd要素のみ」に適用される。

参考サイト

2
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
2
3