의사 클래스라고도 함
:
를 붙여 사용
hover
:hover
- 요소에 마우스가 올라가 있는 동안에만 선택
div:hover {
color: green;
}
active
:active
- 요소를 마우스로 클릭하는 동안에만 선택focus
:focus
- 요소가 포커스 된 동안에만 선택
input
img
tabindex
등 대화형 컨텐츠에서 사용 가능함
input:focus {
color: orange;
}
first-child
:first-child
- 형제 요소 중 첫 번째 요소 선택html
<ul class="fruits">
<li>딸기</li>
<li>수박</li>
<li>망고</li>
<li>사과</li>
</ul>
css
.fruits li:last-child {
color: pink;
}
last-child
:last-child
- 형제 요소 중 마지막 요소 선택html
<ul class="fruits">
<li>딸기</li>
<li>수박</li>
<li>망고</li>
<li>사과</li>
</ul>
css
.fruits li:first-child {
color: pink;
}
nth-child
:nth-child(n)
- 형제 요소 중 n번째 요소 선택
:nth-child(0)
은 없음
html
<ul class="fruits">
<li>딸기</li>
<li>수박</li>
<li>망고</li>
<li>사과</li>
</ul>
css
.fruits li:nth-child(2) {
color: pink;
}
👉 짝수 번째 요소들 선택 ( 이때 n
은 0
부터 시작 )
.fruits li:nth-child(2n) {
color: pink;
}
👉 세 번째 요소부터 이후 요소들 선택 ( 이때 n
은 0
부터 시작 )
.fruits li:nth-child(n+3) {
color: pink;
}
child 주의할 점
html
<div class="fruits">
<div>딸기</div>
<p>수박</p>
<p>망고</p>
<span>사과</span>
</div>
css
.fruits p:nth-child(1) {
color: blue;
}
👆 위와 같이 설정할 경우
.fruits
의 <p>
중 첫 번째 요소인 '수박'이 선택될 것 같지만 실제로는 아무것도 선택되지 않음
→ 명확한 해석을 위해 오른쪽에서 왼쪽으로 읽어야 함
.fruits p:nth-child(1)
→ 자식 요소들 중 첫 번째인데 p태그의 자식요소여야 하고, fruits라는 클래스를 가진 요소의 후손이어야 함
그런데 첫 번째 자식 요소는 <p>
가 아닌 <div>
이므로 선택되지 않았음
❔ .box-group
의 첫 번째 <div>
를 선택하려면
html
<div class="box-group">
<div>1</div>
<div>2</div>
<div>3
<div>3-1</div>
<div>3-2</div>
<div>3-3</div>
</div>
</div>
css
.box-group div:first-child {
color: blue;
}
>
) 사용 .box-group > div:first-child {
color: blue;
}
nth-of-type
:nth-of-type(n)
- 요소의 타입( 태그 이름 )과 동일한 타입인 형제 요소 중 n번째 요소라면 선택html
<div class="fruits">
<div>딸기</div>
<p>수박</p>
<p>망고</p>
<span>사과</span>
</div>
css
.fruits p:nth-of-type(1) { /* p태그 중 첫 번째! */
color: blue;
}
not
부정 선택자
a:not(b)
- a
가 아닌 b
선택
html
<ul class="fruits">
<li>딸기</li>
<li class="watermelon">수박</li> <!-- '수박' 빼고 전부 선택 -->
<li>망고</li>
<li>사과</li>
</ul>
css
.fruits li:not(.watermelon) {
color: green;
}