형제 관계에 있는 요소 중 특정 요소를 선택하는 선택자
!!! 위치를 기준으로 구분함 중요 !!!
:first-child
:last-child
:nth-child(수열)
:nth-last-child(수열)
/* 일반 구조 선택자 */
/* :first-child : 형제 관계의 요소 중 첫번째 요소 */
#test1 > p:first-child {
background-color: red;
color: white;
}
/* :last-child : 형제 관계의 요소 중 마지막 요소 */
#test1 > pre:last-child {
background-color: orange;
}
/* 해석할때 거꾸로 하는게 좋음 */
/* last-child -> pre 인지 아닌지 */
/* nth-child(수열) :
형제 관계 요소 중 지정된 수열 번째 요소를 모두 선택
순서를 따질 때 1부터 시작함
*/
#test1 > p:nth-child(2) {
/* #test1의 자식 요소 중 2번째 요소를 선택하고 p태그인지 확인 */
background-color: yellow;
}
#test1 > p:nth-child(4) {
/* #test1의 자식 요소 중 4번째 요소를 선택하고 p태그인지 확인 */
background-color: green;
}
/* 홀수 번째 형제 요소 선택 */
#test1 > p:nth-child(2n-1) {
font-weight: bold;
font-size: 30px;
}
/* 짝수 번째 형제 요소 선택 */
#test1 > p:nth-child(2n) {
border: 3px solid black;
}
/* :mth-last-child(수열) :
형제 관계 요소 중
뒤에서부터 지정된 수열 번째 요소를 모두 선택
*/
#test1 > p:nth-last-child(2) {
color:hotpink;
}
<div id="test1">
<p>테스트1</p>
<p>테스트2</p>
<p>테스트3</p>
<p>테스트4</p>
<p>테스트5</p>
<pre>테스트6</pre>
</div>
선택된 형제 관계 요소 중 특정 요소를 선택하는 선택자
(선택된 요소들을 기준으로 구분)
:first-of-type : 같이 선택된 형제들 중에서 첫번째 요소
:last-of-type : 같이 선택된 형제들 중에서 마지막 요소
:nth-of-type(수열) : 같이 선택된 형제들 중에서 수열번째 모든 요소
:nth-last-of-type(수열) : 같이 선택된 형제들 중에서 뒤에서 수열번째 모든 요소
/* 형태 구조 선택자 */
/* 해석순서 앞에서부터 차례대로 */
/* :first-of-type */
#test2 > p:first-of-type {
background-color: orange;
}
/* :last-of-type */
#test2 > p:last-of-type {
background-color: skyblue;
}
/* :nth-of-type(수열) */
/* #test2 자식 p태그 중에서 홀수번째 요소의 글자크기 30px 변경 */
#test2 > p:nth-of-type(2n-1) {
font-size: 30px;
}
/* :nth-last-of-type(수열) */
#test2 > p:nth-last-of-type(2n){
background-color: red;
}
<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>
괄호 내 선택자를 제외한 나머지 요소 선택
/* 부정 선택자 */
/* #test3 자식 li 요소 중 3의 배수를 제이한 요소만 선택 */
#test3 > li:not(:nth-of-type(3n)) {
background-color: pink;
}
<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>