CSS의 :last-child 의사 클래스(pseudo-class)는 어떤 부모 요소 안에서 마지막 자식 요소에 해당하는 요소를 선택합니다. 목록의 마지막 항목이나 표의 마지막 열처럼 특정 위치의 요소에만 별도의 스타일을 적용하고 싶을 때 매우 유용하게 활용됩니다.
문법(Syntax)
:last-child 의사 클래스의 기본 문법은 다음과 같습니다.
:last-child {
/* 선언부 */
}그럼 실제 예제를 통해 CSS :last-child 의사 클래스가 어떻게 동작하는지 살펴보겠습니다.
예제 1: 표(Table)의 마지막 열에 스타일 적용하기
아래 예제에서는 td:last-child와 th:last-child 선택자를 사용해 표의 마지막 열 셀에만 오른쪽 테두리를 추가합니다.
<!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:last-child, th:last-child {
border-right: 2px solid black;
}
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>Demo</caption>
<tr>
<th colspan="4">Table</th>
</tr>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
<tr>
<td>Five</td>
<td>Six</td>
<td>Seven</td>
<td>Eight</td>
</tr>
</table>
</body>
</html>실행 결과
:last-child 선택자를 적용하기 전 — 각 셀에는 왼쪽과 위쪽 테두리만 있어서 표의 오른쪽 가장자리가 열려 있는 것을 확인할 수 있습니다.

:last-child 선택자를 적용한 후 — td:last-child, th:last-child 덕분에 마지막 열의 셀에도 오른쪽 테두리가 생겨 표 전체가 완전히 닫힌 형태로 표시됩니다.

이번에는 목록(list) 요소에 :last-child 의사 클래스를 적용하는 또 다른 예제를 살펴보겠습니다.
예제 2: 목록(List)의 마지막 항목에 스타일 적용하기
아래 예제는 :first-child, :nth-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>
<h2>What is PHP?</h2>
<ul>
<li>PHP is a recursive acronym for "PHP: Hypertext Preprocessor".</li>
<li>PHP is a server side scripting language that is embedded in HTML.</li>
<li>It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.</li>
</ul>
</body>
</html>실행 결과
첫 번째 항목은 :first-child에 의해 연한 분홍색(seashell) 배경이, 두 번째 항목은 :nth-child(2)에 의해 하늘색(azure) 배경이, 그리고 마지막 항목은 :last-child에 의해 초록색(springgreen) 배경과 지정된 글꼴이 각각 적용된 것을 확인할 수 있습니다.

정리
:last-child는 부모 요소의 마지막 자식만 정확히 골라내는 강력한 선택자입니다. 참고로 같은 계열의 의사 클래스인 :first-child(첫 번째 자식), :nth-child(n)(n번째 자식), :only-child(유일한 자식) 등을 함께 익혀두면 반복되는 HTML 구조에서 불필요한 클래스 추가 없이 깔끔하게 스타일을 제어할 수 있습니다.