# nth-childとnth-of-typeの違いを理解する

Table of Contents

nth-child

親要素内のすべての子要素に対して適用され、その中から条件に一致する要素が選択される。 そのため要素の種類に関係なく、すべての子要素が考慮される。

nth-of-type

親要素内の特定の要素タイプ(タグ名)に対して適用され、その中から条件に一致する要素が選択される。 そのため要素の種類に基づいて選択がされる。

具体例

例えば以下のコードがあった時、

<div class="example">
<div>Item 1</div>
<p>Item 2</p>
<div>Item 3</div>
<p>Item 4</p>
<div>Item 5</div>
</div>

nth-child

.example div:nth-child(3) {
color: red;
}

この場合、.example内の直下のdiv要素の中から、3番目の要素(“Item 3”)が赤くなる。

nth-of-type

.example div:nth-of-type(3) {
color: blue;
}

この場合、.example内の直下のdiv要素の中から、同じ種類の要素の中で3番目の要素(“Item 5”)が青くなる。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments