:first-child
:last-child
:nth-child(수열)
:nth-last-child(수열)
뒤에 선택자가 먼저 해석된다
예시 확인을 위한 <div>
<div id="test1">
<p>테스트1</p>
<p>테스트2</p>
<p>테스트3</p>
<p>테스트4</p>
<p>테스트5</p>
<pre>테스트6</pre>
</div>
형제 관계의 요소 중 첫 번째 요소
#test1 > p:first-child {
background-color: red;
color: white;
}
➡️ test1이라는 아이디를 가진 자식 중에 첫 번째 자식이 p태그이면 적용해라
형제 관계의 요소 중 마지막 요소
#test1 > p:last-child {
background-color: orange;
}
➡️ test1이라는 아이디를 가진 자식들 중에 마지막 자식이 p태그면 바꿔라
➡️ 마지막 자식이 p태그가 아니기 때문에 선택이 안되고 아무일도 일어나지 않음
#test1 > pre:last-child {
background-color: orange;
}
➡️ pre가 마지막 자식이기 때문에 선택됨
#test1 > p:nth-child(2) {
background-color: yellow;
}
➡️ test 1의 자식 요소 중 2번째 요소를 선택하고, p태그인지 검사
#test1 > p:nth-child(4) {
background-color: green;
}
➡️ test1의 자식 요소 중 4번째 요소를 선택하고, p태그인지 검사
#test1 > p:nth-child(2n-1) {
font-weight: bold;
font-size: 30px;
}
➡️ 홀수번째 형제 요소 선택
#test1 > p:nth-child(2n) {
border: 3px solid black;
}
➡️짝수번째 형제 요소 선택
#test1 > p:nth-last-child(2) {
color: hotpink;
}
➡️ 뒤에서 두 번째가 p태그일 때 적용
선택된 형제 관계 요소 중 특정 요소를 선택하는 선택자
선택된 요소들을 기준으로 구분
예시 확인을 위한 div
<div id="test2">
<pre>테스트0</pre>
<p>테스트1</p>
<p>테스트2</p>
<p>테스트3</p>
<p>테스트4</p>
<p>테스트5</p>
<pre>테스트6</pre>
</div>
#test2 > p:first-of-type {
background-color: orange;
}
➡️ test 2라는 요소를 가진 요소들 중 p태그 중에 first-of-type 요소를 먼저 선택
(여기서는 p태그 먼저 해석)
➡️ 테스트2
#test2 > p:last-of-type {
background-color: skyblue;
}
➡️ p태그 중에 마지막
➡️ 테스트 5
#test2 > p:nth-of-type(2n-1){
font-size: 30px;
}
➡️ #test2의 자식 p태그 중에서 홀수번째 요소의 글자크기 30px로 변경
#test2 > p:nth-last-of-type(2n){
background-color: red;
}
➡️ #test2의 자식 p태그 중에서 짝수번째 요소의 배경색을 빨간색으로 변경
선택자1:not(선택자2))
<예시 확인을 위한 코드>
<ul id="test3">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
#test3 > li:not(:nth-of-type(3n)){
background-color: aqua;
}
➡️test3의 li 중 소괄호 내에 작성된 걸 제외하고 나머지 요소
➡️ #test3의 자식 li요소 중 3의 배수를 제외한 요소만 선택