CSS :first-child
의사 클래스는 형제 요소 중 제일 첫 요소를 나타냅니다.
/* Selects any <p> that is the first element
among its siblings */
p:first-child {
color: lime;
}
참고: 초기 정의에서는 부모가 있는 요소만 선택할 수 있었습니다. Selectors Level 4부터는 이 제한이 사라졌습니다.
구문
:first-child
예제
기본 예제
HTML
<div>
<p>This text is selected!</p>
<p>This text isn't selected.</p>
</div>
<div>
<h2>This text isn't selected: it's not a `p`.</h2>
<p>This text isn't selected.</p>
</div>
CSS
p:first-child {
color: lime;
background-color: black;
padding: 5px;
}
결과
목록 스타일링
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li>
<li>Item 3.3</li>
</ul>
</li>
</ul>
CSS
ul li {
color: blue;
}
ul li:first-child {
color: red;
font-weight: bold;
}
결과
명세
Specification | Status | Comment |
---|---|---|
Selectors Level 4 The definition of ':first-child' in that specification. |
Working Draft | Matching elements are not required to have a parent. |
Selectors Level 3 The definition of ':first-child' in that specification. |
Recommendation | No change. |
CSS Level 2 (Revision 1) The definition of ':first-child' in that specification. |
Recommendation | Initial definition. |
브라우저 호환성
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.