【CSS】nth-childとnth-of-typeの違いとクラスへ直接指定はできない事について

疑似要素nth-of-typeとnth-childの違いとその例です。

まずは.content-bodyの中に.content-boxを作っておきます。.content-boxはあえてspanで作ったものとdivで作ったものの2つを用意しました。

<div class="content-body">
	<span>span</span>
	<div>div</div>
	<div>div</div>
	<div>div</div>
	<div>div</div>
</div>
.content-body{
	display: flex;
	background-color:#ccc;
	width:100%;
	min-height:300px;
}
 
.content-body span{
	width:100px;
	height:100px;
	background-color:#ddd;
	border:1px solid #666;
}
 
.content-body div{
	display:block;
	width:100px;
	height:100px;
	background-color:#999;
	border:1px solid #666;
}
span
div
div
div
div

nth-of-type「指定したセレクタを数える」

nth-of-typeは指定したセレクタを数えます。ここでは、div:nth-of-type(3)なのでセレクタはdivを指定し、3番目のdivの背景色を変えています。

  • セレクタ:nth-of-type(指定したセレクタの何番目)
<div class="content-body">
	<span>span</span>
 
	/*nth-of-typeはここからdivの数を数える*/
	<div>div</div>
	<div>div</div>
	<div>div</div>/*nth-of-typeの3つ目*/
	<div>div</div>
</div>
/*divにnth-of-typeで3番目の背景を薄いピンクに*/
.content-body div:nth-of-type(3){
	background-color:#ffcccc;
}
span
div
div
div
div

nth-child「全てのセレクタを数える」

nth-childは全てのセレクタを数えます。ここでは、div:nth-child(3)なのでセレクタはdivを指定しています。ただ、nth-of-typeと違い、指定した兄弟関係にある全ての要素を数えます。ですので、セレクタはdivを指定していますが、実際には.content-bodyの中の3番目の背景色を変えています。

  • セレクタ:nth-child(兄弟関係の何番目)
<div class="content-body">
 
	/*nth-childはここから全てのセレクタを数を数える*/
	<span>span</span>
	<div>div</div>
	<div>div</div>/*nth-childの3つ目*/
	<div>div</div>
	<div>div</div>
</div>
/*divにnth-childで3番目の背景を薄いピンクに*/
.content-body div:nth-child(3){
	background-color:#ffcccc;
}
span
div
div
div
div

注)クラスを指定するとそのクラスの要素の指定になる

nth-of-type、nth-child共にセレクタを指定するのであって、クラス自体を直接指定できません。クラスを指定した場合はそのクラスの要素が指定要素になります。

ここでは、各要素にクラス.box1と.box2を設定し、クラス.box2にnth-of-type、nth-childを指定してみます。.box1はあえてspanとdivも利用してみました。

<div class="content-body">
 
	/*nth-childはここから全てのセレクタを数を数える*/
	<span class="box1">.box1</span>
 
	/*nth-of-typeはここからdivの数を数える*/
	<div class="box1">.box1</div>
	<div class="box2">.box2</div>/*nth-childの3つ目*/
	<div class="box2">.box2</div>/*nth-of-typeの3つ目*/
	<div class="box2">.box2</div>
</div>
/*.box2にnth-childで3番目の背景を薄いピンクに*/
.box2:nth-child(3){
	background-color:#ffcccc;
}
 
/*.box2にnth-of-typeで3番目の背景を薄いブルーに*/
.box2:nth-of-type(3){
	background-color:#99cccc;
}

nth-childは「全てのセレクタを数える」だけなので、クラスで指定しようがその兄弟関係にある全ての要素の中で何番目か、を指定します。ですので、.content-bodyの中の3番目の背景色が薄いピンクに変わるという結果になります。

nth-of-typeは「指定したセレクタを数える」のですが、クラスの要素が指定要素になるので、.content-bodyの中の3番目のdivの背景色が薄いブルーに変わるという結果になります。

.box1
.box1
.box2
.box2
.box2

ちなみに、2つ目もdivからspanへ変更すると、当然ながら.content-bodyの中の3番目のdivは1つ右にずれるます。

<div class="content-body">
	/*nth-childはここから全てのセレクタを数を数える*/
	<span class="box1">.box1</span>
 
	/*divからspanへセレクタを変更*/
	<span class="box1">.box1</span>
 
	/*nth-of-typeはここからdivの数を数える*/
	<div class="box2">.box2</div>/*nth-childの3つ目*/
	<div class="box2">.box2</div>
	<div class="box2">.box2</div>/*nth-of-typeの3つ目*/
</div>
.box1 .box1
.box2
.box2
.box2

Yuki Nakata

中田デザイン事務所 代表。
WEBデザイナー(フリー)/ WEB講師(非常勤)/ 海外販売(法人)他

お仕事のご相談はお問い合わせフォームへお願いします。