CSS의 nth-child 선택자를 평소 잘 쓰지않다가 우연히 발견한 선택자 방식(?)이 있어 정리해봄
이 선택자는 특정 부모 요소의 직계 자식 요소들 중에서 지정한 클래스명을 가진 요소들만 대상으로 하여, 그중 n 번째 요소를 선택하는 방식이다.
ex) 선택X
<div class="box">
<p class="text">첫 번째 문단</p>
<div class="item">첫 번째 아이템</div>
<div class="item">두 번째 아이템</div>
</div>
/* 태그 ❌ */
.box div:nth-child(1) {
color: red;
font-weight: bold;
}
/* 클래스 ❌ */
.item:nth-child(1) {
color: red;
font-weight: bold;
}
👆 item 선택 안 됨
위 예시 코드에 nth-child(n of className)를 사용해보자.
div:nth-child(1 of .item) {
color: red;
font-weight: bold;
}
👆 위와 같이 잘 적용되는 것을 볼 수 있다.
참고로 nth-last-child(n of className) 도 된다.
ex) .special 클래스가 있는 요소들 중에서 첫 번째 요소만 선택
<ul>
<li class="item">첫 번째 아이템</li>
<li class="special">특별한 아이템 1</li>
<li class="item">두 번째 아이템</li>
<li class="special">특별한 아이템 2</li>
<li class="item">세 번째 아이템</li>
</ul>
li:nth-child(1 of .special) {
color: red;
font-weight: bold;
}
💡 CSS Level 4에서 추가된 기능으로, 최신 브라우저에서만 지원되기 때문에
사용 전에는 반드시 브라우저 호환성을 확인할 것!😎