Next.js로 하던 프로젝트에서 위와 같은 경고 문구가 떳다. SSR 환경에서 first-child
는 unsafe
하니까 first-of-type
으로 바꿔라고 한다.
바꾸니까 경고 문구가 사라지고, 제대로 동작하는 것을 볼 수 있었다. 그래서 first-of-type이 뭔데?
The :first-child CSS pseudo-class represents the first element among a group of sibling elements. -MDN
The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements. -MDN
first-child
는 자식 요소 중 첫 번째를 선택하는 가상클래스이고, first-of-type
은 자식 요소 중에서 type
이 일치하는 것들 중 첫 번째를 선택하는 가상클래스라고 한다. 아래의 HTML 코드를 예시로 들어보자.
<div class="parent">
<div>first div</div>
<p>first p</p>
<p>second p</p>
</div>
나는 <p>
중 첫 번째 자식인<p>first p</p>
의 배경을 pink
로 바꾸고 싶다.
.parent p:first-child {
background-color: pink;
}
결과는 ?
의도했던 대로 되지 않는다. parent
의 first-child
는 <div>first div</div>
이므로 p:first-child
가 적용이 안되는 것. p:second-child
로 해결할 수 있다.
.parent p:second-child {
background-color: pink;
}
뭔가 애매하지만 되긴 된다. 이런 애매함을 없애고 싶을 때 사용하는 것이 first-of-type
이다.
.parent p:first-of-type {
background-color: pink;
}
nth-of-type(n)
으로도 사용할 수 있다.