티스토리 뷰

이론/CSS

[CSS3] nth-child와 nth-of-type의 차이

millfeel1298 2021. 10. 28. 11:00

:nth-child

태그의 종류에 상관없이 형제 순서로 선택을 한다.

See the Pen [CSS3] :nth-child by mill (@millfeel) on CodePen.

 

 

<div class="item">out item1 - div</div>
<ul>
  <li class="item">inner item1 - li</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li class="item">inner item2 - li</li>
</ul>
<p class="item">out item2 - p</p>
<div><!-- 비어있음 --></div>
<div class="item">out item3 - div</div>
.item:nth-child(1) { color: red; }
.item:nth-child(2) { color: blue; }

*out item1 - div는 <body>의 첫번째 자식이고, inner item1 - li는 <ul>의 첫번째 자식이다.

*.item:nth-child(2) { color: blue; }가 적용되지 않은 이유는 <body> 기준 두번째 자식은 <ul>이고, <ul> 기준 두번째 자식은 <li>2</li>인데, 두 요소 모두 item class가 없기 때문에 적용되지 않는다.

 


:nth-of-type

태그로 구분해서 형제 순서를 나누고 선택을 한다.

See the Pen [CSS3] :nth-of-type by mill (@millfeel) on CodePen.

 

 

<div class="item">out item1 - div</div>
<ul>
  <li class="item">inner item1 - li</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li class="item">inner item2 - li</li>
</ul>
<p class="item">out item2 - p</p>
<div><!-- 비어있음 --></div>
<div class="item">out item3 - div</div>
.item:nth-of-type(1) { color: red; }
.item:nth-of-type(3) { color: blue; }

*:nth-child와는 달리 각 요소의 첫번째이면서 item class가 붙은 <div>, <li>, <p>에 color: red가 적용됐다.

*:nth-of-type은 태그끼리 형제관계를 만들기 때문에 .item:nth-of-type(3)은 div 중에서 3번째 형제이면서 item class가 붙은 "out item3 - div"에 color: blue가 적용된다.


[요약]
:nth-child는 <tag> 안가리고 형제 맺고, :nth-of-type은 <tag> 가리며 형제 맺는다.

https://flukeout.github.io/

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함