css 〇番目のクラスに何かしたい(疑似要素: first-of-type, first-child, last-of-type, last-child、nth-of-type())

作成日:2023-01-31, 更新日:2023-01-31

基本

first-child / last-child 「最初 / 最後」の子要素
first-of-type / last-of-type 「指定した要素の中」で「最初 / 最後」の子要素 タグのみ。クラスは設定不可
nth-of-type() 指定した子要素で「〇番目」の子要素

サンプル

<div id="hoge">
  <p>123</p>
  <div class="foo">abc</div>
  <div class="foo">def</div>
  <div class="foo">ghi</div>
  <p>456</p>
</div>

「<p>123</p>」を指定したいときの例たち

.hoge p:first-child { ~ 省略 ~ }
/*
.hoge p:first-of-type { ~ 省略 ~ }
.hoge p:nth-of-type(1) { ~ 省略 ~ }
*/

「<p>456</p>」を指定したいときの例たち

.hoge p:last-child { ~ 省略 ~ }
/*
.hoge p:last-of-type { ~ 省略 ~ }
.hoge p:nth-of-type(2) { ~ 省略 ~ }
*/

「<div class="foo">abc</div>」を指定したいときの例たち

.hoge div:first-of-type { ~ 省略 ~ }
/*
.hoge .foo:nth-of-type(1) { ~ 省略 ~ }
.hoge div:nth-of-type(1) { ~ 省略 ~ }
*/

「<div class="foo">def</div>」を指定したいときの例たち

.hoge .foo:nth-of-type(2) { ~ 省略 ~ }
/*
.hoge div:nth-of-type(2) { ~ 省略 ~ }
*/

「<div class="foo">ghi</div>」を指定したいときの例たち

.hoge div:last-of-type { ~ 省略 ~ }
/*
.hoge .foo:nth-of-type(3) { ~ 省略 ~ }
.hoge div:nth-of-type(3) { ~ 省略 ~ }
*/

関連項目