Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS :nth-child() 의사 클래스 완벽 정리 – n번째 자식 요소 선택하기

CSS :nth-child() 의사 클래스(가상 클래스)는 부모 요소 안에서 n번째 자식에 해당하는 요소를 선택할 때 사용합니다. 특정 순서의 요소만 골라 색상이나 폰트 등 다른 스타일을 적용해야 할 때 매우 유용하며, 리스트·테이블·카드 레이아웃 등에서 널리 활용됩니다.

문법(Syntax)

기본 문법은 다음과 같습니다.

:nth-child(n){
    /* 선언부 */
}

괄호 안에는 숫자뿐 아니라 odd, even, 또는 2n+1 같은 수식도 지정할 수 있어, 짝수/홀수 번째 항목을 일괄 선택하는 것도 가능합니다.

예제 1 – 박스 요소에 순서별 배경색 적용하기

다음 예제에서는 여섯 개의 자식 div에 각각 다른 배경색을 지정합니다.

<!DOCTYPE html>
<html>
<head>
<title>CSS :nth-child() Pseudo Class</title>
<style>
form {
    width:70%;
    margin: 0 auto;
    text-align: center;
}
* {
    padding: 2px;
    margin:5px;
    box-sizing: border-box;
}
input[type="button"] {
    border-radius: 10px;
}
.child{
    display: inline-block;
    height: 40px;
    width: 40px;
    color: white;
    border: 4px solid black;
}
.child:nth-child(1){
    background-color: #FF8A00;
}
.child:nth-child(2){
    background-color: #F44336;
}
.child:nth-child(3){
    background-color: #C303C3;
}
.child:nth-child(4){
    background-color: #4CAF50;
}
.child:nth-child(5){
    background-color: #03A9F4;
}
.child:nth-child(6){
    background-color: #FEDC11;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS :nth-child() Pseudo Class</legend>
<div id="container">
<div class="child"></div><div class="child"></div><div class="child"></div><div class="child"></div><div class="child"></div><div class="child"></div>
</div><br>
</body>
</html>

출력 결과

위 코드를 실행하면 각 박스가 지정된 순서대로 서로 다른 색상으로 표시됩니다.

CSS :nth-child() 의사 클래스 완벽 정리 – n번째 자식 요소 선택하기

예제 2 – 목록 항목에 첫 번째·두 번째·마지막 스타일 적용하기

이번 예제에서는 :nth-child(2)와 함께 :first-child, :last-child를 조합하여 목록의 위치별로 배경색과 글꼴을 다르게 지정합니다.

<!DOCTYPE html>
<html>
<head>
<style>
* {
    font-size: 1.1em;
    list-style: circle;
}
li:first-child {
    background-color: seashell;
    font-family: cursive;
}
li:nth-child(2) {
    background-color: azure;
    font-family: "Brush Script Std", serif;
}
li:last-child {
    background-color: springgreen;
    font-family: "Gigi", Arial;
}
</style>
</head>
<body>
<p>유명 크리켓 경기장</p>
<ul>
<li>Eden Gardens, Kolkata, India</li>
<li>Melbourne Cricket Ground, Melbourne, Australia</li>
<li>DY Patil Sports Stadium, Navi Mumbai, India</li>
</ul>
</body>
</html>

출력 결과

실행하면 첫 번째 항목은 seashell 배경, 두 번째 항목은 azure 배경, 마지막 항목은 springgreen 배경으로 각각 다르게 표시됩니다.

CSS :nth-child() 의사 클래스 완벽 정리 – n번째 자식 요소 선택하기

정리

:nth-child()는 단순히 특정 번째 요소를 고르는 것을 넘어, nth-child(odd)(홀수), nth-child(even)(짝수), nth-child(3n)(3의 배수)처럼 패턴 기반 선택도 지원합니다. 이를 잘 활용하면 반복되는 UI 요소를 손쉽게 구분하고, 줄무늬 테이블이나 그리드 레이아웃 같은 디자인을 별도의 클래스 없이 CSS만으로 구현할 수 있습니다.