구조 가상 클래스
① 특정 위치 자식 요소 선택
요소가 여러 개 나열되어 있는 경우 class, id를 사용하지 않고
요소가 몇 번째인지 따져서 스타일 적용이 가능하다.
| :only-child | 부모 안에 자식 요소가 하나뿐일 때 |
| A:only-type-of | 부모 안에 A 요소가 하나뿐일 때 |
| :first-child | 부모 안에 있는 모든 요소 중 첫 번째 자식 요소 |
| :last-child | 부모 안에 있는 모든 요소 중 마지막 자식 요소 |
| A:first-of-type | 부모 안에 있는 A 요소 중 첫 번째 요소 |
| A:last-of-type | 부모 안에 있는 A 요소 중 마지막 요소 |
| :nth-child(n) | 부모 안에 있는 모든 요소 중 n번째 자식 요소 |
| :nth-last-child(n) | 부모 안에 있는 모든 요소 중 뒤에서 n번째 자식 요소 |
| A:nth-of-type(n) | 부모 안에 있는 A 요소 중에서 n번째 요소 |
| A:nth-last-of-type(n) | 부모 안에 있는 A 요소 중에서 뒤에서 n번째 요소 |
<style>
.contents :first-child { /*contents 안의 모든 요소 중 첫 번째 자식인 <h2>홈</h2>에 스타일 적용*/
background-color: red;
}
.contents :nth-child(3) { /*contents 안의 모든 요소 중 세 번째 자식인 <p>Qui...</p>에 스타일 적용*/
background-color: yellow;
}
.contents p:nth-of-type(3) { /*contents 안의 p 태그들 중 3번째 p 태그인 <p>Irure...</p>에 스타일 적용*/
background-color: skyblue;
}
.contents p:nth-last-of-type(1) { /*contents 안의 p 태그들 중 뒤에서 1번째 p 태그인 <p>Fugiat...</p>에 스타일 적용*/
background-color:pink;
}
</style>
<div class="contents">
<h2>홈</h2>
<p>Excepteur...</p>
<p>Qui...</p>
<h2>베스트</h2>
<p>Irure...</p>
<h2>신제품</h2>
<p>Fugiat...</p>
</div>

② 수식을 사용해 위치 지정하기
위치 지정할 때 반복된 규칙을 찾아서 수식을 사용할 수도 있다.
예를 들어,
홀수 번째에 스타일 줄 때는 :nth-child(odd) 또는 :nth-child(2n+1)
짝수 번째에 스타일 줄 때는 :nth-child(even) 또는 :nth-child(2n)
으로 작성할 수 있다.
<style>
table tr:nth-of-type(2n+1) { /*table의 모든 자식 tr 중 홀수 번째에만 스타일 적용*/
background-color: pink;
}
</style>
<div id="container">
<h1>학과</h1>
<table>
<tr>
<td>컴퓨터공학과</td>
</tr>
<tr>
<td>인터넷보안과</td>
</tr>
<tr>
<td>정보통신공학과</td>
</tr>
<tr>
<td>사회복지과</td>
</tr>
<tr>
<td>실용음악과</td>
</tr>
<tr>
<td>세무회계과</td>
</tr>
</table>
</div>

더보기
Do it! HTML+CSS+자바스크립트 웹 표준의 정석 교재를 참고하여 작성했다.