[CSS] 알아두면 유용한 nth-child 정복하기 😎(feat. nth-of-type)
· 4 min read
항상 nth-child(숫자)만 사용하세요??
div > div
===div > div:nth-child(n + 1)
왜 같은지 알아보고 다른 유용한 문법도 알아갑시다. 🤓
:nth-child
예제로 사용할 동그라미의 구조
<div> // Circle Wrapper
<div /> // Circle
<span>{숫자}</span>
</div>
:nth-child(숫자)
& > div:nth-child(5) > div {
background-color: cornflowerblue;
}
가장 기본적이고 가장 많이 쓰이는 nth-child 문법이다.
:nth-child(5)
를 사용하면 특정 숫자번째의 자식을 지정해서 스타일을 바꿀 수 있다.
:nth-child(n + 숫자)
& > div:nth-child(n + 3) > div {
background-color: cornflowerblue;
}
숫자
번째를 포함한 이후의 모든 자식에게 스타일을 적용할 수 있다.
:nth-child(-n + 숫자)
& > div:nth-child(-n + 6) > div {
background-color: cornflowerblue;
}
이전의 방법의 반대케이스이다.
숫자
번째를 포함한 이전의 모든 자식에게 스타일을 적용 할 수 있다.
:nth-child(n + 숫자):nth-child(-n + 숫자)
& > div:nth-child(n + 3):nth-child(-n + 6) > div {
background-color: cornflowerblue;
}
위의 두 가지 방법을 합친 케이스이다. n번째 자식을 포함한 이후의 모든 자식에 대해서 m번째를 포함한 이전의 모든 자식에게 스타일을 적용한 것이다. n번부터 m번까지 범위를 정하고 싶을때 유용하다.
:nth-child(odd)
& > div:nth-child(odd) > div {
background-color: cornflowerblue;
}
모든 홀수번째 자식에게 스타일을 적용하는 방법이다.
:nth-child(even)
& > div:nth-child(even) > div {
background-color: cornflowerblue;
}
모든 짝수번째 자식에게 스타일을 적용하는 방법이다.
:nth-child(n + 숫자):nth-child(odd):nth-child(-n + 숫자)
& > div:nth-child(n + 2):nth-child(odd):nth-child(-n + 9) > div {
background-color: cornflowerblue;
}
위의 세 가지 방법을 합친 케이스이다. 특정 범위 안에서 홀수 혹은 짝수의 자식들에게 스타일을 적용하는 방법이다.
:nth-child(An + B)
& > div:nth-child(3n + 1) > div {
background-color: cornflowerblue;
}
B번 자식부터 A개 띄어서 스타일을 적용하는 방법이다.
nth-child(An + B):nth-child(even)
& > div:nth-child(3n + 1):nth-child(even) > div {
background-color: cornflowerblue;
}
위의 케이스에서 짝수번 자식들에게만 스타일을 적용하는 방법이다.
nth-of-type
예제로 사용할 네모의 구조
<span> // Square Wrapper
<span /> // Square
<span>{숫자}</span>
</div>
nth-of-type(숫자)
& > div:nth-of-type(3) > div {
background-color: cornflowerblue;
}
& > span:nth-of-type(4) > span:first-child {
background-color: coral;
}
nth-child(숫자)
와는 다르게 모든 자식에 대해서가 아니라 같은 타입(태그)인 자식에 대해서 특정한 숫자번째 자식을 고를 수 있다.
div:nth-of-type(n + A), span:nth-of-type(Bn + C)
& > div:nth-of-type(n + 3) > div {
background-color: cornflowerblue;
}
& > span:nth-of-type(3n + 2) > span:first-child {
background-color: coral;
}
nth-child
에서와 마찬가지로nth-of-type
에도 같은 문법을 적용할 수 있다.
나머지 문법들도 동일하게 적용되므로 nth-of-type
은 여기에서 마치겠다. 😜