HooneyLog
© 2026 Seunghoon Shin. All rights reserved.
모든 게시글
CSS
2022. 9. 10.•
2

nth-of-type vs nth-child

Seunghoon Shin
작성자 Seunghoon Shin풀스택 개발자

CSS에서 자신이 어느 순서에 속하는지 선택하는 가상 클래스가 존재한다.

그것이 바로 nth-of-type과 nth-child가 있다.

지금까지 만약 이런 상황을 직면하게 되었을때 nth-child를 주로 사용해왔는데, nth-of-type이라는것도 있다는것을 알게되었으며, 이 둘의 차이점을 정리하고자 한다.

nth-of-type이란?

  • 부모 엘리먼트 내 자신의 엘리먼트가 몇번째인지를 판단해서 적용하는 것이다.

예시

p:nth-of-type(1) { font-weight: bold; } <div> <div>This element isn't counted.</div> <p>1st paragraph.</p> // 이곳을 선택하게 된다. <p class="fancy">2nd paragraph.</p> <div>This element isn't counted.</div> <p class="fancy">3rd paragraph.</p> <p>4th paragraph.</p> </div>

아래 처럼 div안에 여러 요소들이 있지만 nth-of-type(1)이므로 p 요소 중에 가장 첫번째인 것이 선택되게 된다.

nth-child 란?

  • 부모 엘리먼트 내 존재하는 모든 자식들중 n번째를 선택하게된다.

예시

p:nth-child(2) { font-weight: bold; } <div> <div>This element isn't counted.</div> <p>1st paragraph.</p> // 이곳을 선택하게 된다. <p class="fancy">2nd paragraph.</p> <div>This element isn't counted.</div> <p class="fancy">3rd paragraph.</p> <p>4th paragraph.</p> </div>

위 nth-of-type과 달리 1st paragraph를 content로 가지는 요소는 2번째 자식 요소이기떄문에 nth-child(2)로 접근을 해야한다.

결론

  • 두개의 가상클래스 모두 자식 요소에서 순서를 선택하여 스타일링을 하는 것이지만, 자식 요소에 어떠한 종류들의 요소가 들어있냐에 따라 n 값이 달라지게 된다.
  • 때문에, 자신이 마크업한 상황을 보고 적절하게 사용하면 된다.
← 이전 글CSS Combinators
다음 글 →속성 선택자