first-child vs first-type-of

김기영·2022년 1월 19일
1

CSS 궁금증

목록 보기
2/2

🐛first-child 경고

Next.js로 하던 프로젝트에서 위와 같은 경고 문구가 떳다. SSR 환경에서 first-childunsafe 하니까 first-of-type으로 바꿔라고 한다.

바꾸니까 경고 문구가 사라지고, 제대로 동작하는 것을 볼 수 있었다. 그래서 first-of-type이 뭔데?

📝first-child vs 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;
}

결과는 ?

의도했던 대로 되지 않는다. parentfirst-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)으로도 사용할 수 있다.

profile
FE Developer

0개의 댓글