CSS :first-child 의사 클래스는 어떤 부모 요소의 첫 번째 자식 요소에 해당하는 요소를 선택하는 선택자입니다. 목록의 첫 항목이나 테이블의 첫 번째 열처럼 특정 위치에 있는 요소만 다르게 스타일링하고 싶을 때 매우 유용하게 활용됩니다.
문법(Syntax)
:first-child 의사 클래스의 기본 문법은 다음과 같습니다.
:first-child{
/*선언부*/
}
예제 1: 테이블 첫 번째 열 스타일링하기
다음은 :first-child 의사 클래스를 사용하여 테이블의 첫 번째 셀(td, th)에서만 왼쪽 테두리를 제거하는 예제입니다.
<!DOCTYPE html>
<html>
<head>
<style>
table {
margin: auto;
padding: 10px;
border: hsl(54, 100%, 50%) solid 13px;
border-radius: 6px;
text-align: center;
}
td, th {
border-left: 2px solid black;
border-top: 3px solid black;
}
td:first-child, th:first-child {
border-left: none;
}
th {
background-color: lightblue;
border-top: none;
}
caption {
margin-top: 3px;
background-color: purple;
caption-side: bottom;
color: white;
border-radius: 20%;
}
</style>
</head>
<body>
<table>
<caption>MCA Syllabus</caption>
<tr>
<th colspan="4">Subjects</th>
</tr>
<tr>
<td>C</td>
<td>C++</td>
<td>Java</td>
<td>C#</td>
</tr>
<tr>
<td>MySQL</td>
<td>PostgreSQL</td>
<td>MongoDB</td>
<td>SQLite</td>
</tr>
</table>
</body>
</html>
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
:first-child 의사 클래스 적용 전 −

:first-child 의사 클래스 적용 후 −

적용 전에는 모든 셀에 왼쪽 테두리가 있었지만, 적용 후에는 각 행의 첫 번째 셀에서만 왼쪽 테두리가 사라진 것을 확인할 수 있습니다.
예제 2: 리스트 항목별로 다른 스타일 적용하기
이번에는 :first-child와 함께 :nth-child(2), :last-child를 조합하여 목록(li) 항목마다 서로 다른 배경색과 글꼴을 지정하는 예제를 살펴보겠습니다.
<!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>
<h2>Apache Spark</h2>
<ul>
<li>Apache Spark is a lightning-fast cluster computing technology, designed for fast computation. </li>
<li>It is based on Hadoop MapReduce.</li>
<li>It extends the MapReduce model to efficiently use it for more types of computations.
</li>
</ul>
</body>
</html>
실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

이처럼 :first-child는 목록의 첫 번째 항목을, :nth-child(2)는 두 번째 항목을, :last-child는 마지막 항목을 각각 선택하므로, 항목의 위치에 따라 개성 있는 디자인을 손쉽게 구현할 수 있습니다.