달력

5

« 2025/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2022. 11. 19. 23:32

nth-child 와 nth-of-type 차이 카테고리 없음2022. 11. 19. 23:32

nth-child와 nth-of-type 이라 했지만

first-child, first-of-type이나

last-child, last-of-type등 모든요소에서 공통적으로 적용되는 개념이다.

 

간단하게 비교를 해보자면

nth-child(n)  nth-of-type(n)
 부모 엘리먼트의 모든 자식 엘리먼트중 n번째  부모 엘리먼트의 특정 자식 엘리먼트중 n번째

 

이론적인 개념만 봐서는 확 와닿지 않으니 바로 적용예제를 통해 비교해보자!

우선 기본세팅은 아래와 같다.

1
2
3
4
5
6
7
<div class="box">
    <p>1. p태그1</p>
    <span>2. span태그1</span>
    <p>3. p태그2</p>
    <span>4. span태그2</span>
    <p>5. p태그3</p>
</div>
 

출력물

 

여기서 5.p태그3의 글씨 색깔을 바꾸는것으로 사용방법을 비교해보겠다.

 

nth-child을 이용해서 글씨색깔을 빨간색으로 바꿔보자!

1
2
3
.box > p:nth-child(5){
    color:red;
}
 

 

 

nth-child는 모든 요소를 포함해서 순서를 카운팅한다.

따라서 5번째 요소를 nth-child로 선택하려면 p:nth-child(5)

 

nth-of-type으로 글씨색깔을 바꾸려면??

1
2
3
.box > p:nth-of-type(3){
    color:blue;
}
 

 

결과물

 

nth-of-type은 특정 요소만을 순서 카운팅한다.

따라서 5번째 요소를 nth-of-type로 선택하려면 p:nth-of-type(3)

 

nth-child는 p와 span태그 두개다 순서에 포함시켰기에 p:nth-child(5)

nth-of-type은 p태그만을 순서에 포함시켰기에 p:nth-child(3)

 

 

[ 참고한사이트 ]

https://www.w3schools.com/cssref/sel_nth-child.asp

https://www.w3schools.com/cssref/sel_nth-of-type.asp

:
Posted by Habba