CSS_04_CSS선택자4

송지윤·2024년 1월 16일

CSS

목록 보기
17/20

일반 구조 선택자

형제 관계에 있는 요소 중 특정 요소를 선택하는 선택자
위치를 기준으로 구분함

:first-child

형제 관계의 요소 중 첫번째 요소

:last-child

형제 관계의 요소 중 마지막 요소
마지막 태그가 지정한 태그가 아니면 바뀌지 않음

:nth-child(수열)

형제 관계 요소 중 지정된 수열번째 요소를 모두 선택
-> 순서 따질 때 1부터 시작

:nth-last-child(수열)

형제 관계 요소 중 뒤에서부터 지정된 수열 번째 요소를 모두 선택

해석 순서 : n번째 요소가 지정한 태그

<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: pink;
}

#test1 > p:last-child {
    background-color: blue;
}

#test1 > pre:last-child {
    background-color: orange;
}

#test1 > p:nth-child(2) {
    background-color: yellow;
}

#test1 > p:nth-child(4) {
    background-color: green;
}

#test1 > p:nth-last-child(2) {
    color: hotpink;
}

홀수번째 형제 요소 선택

css code

#test1 > p:nth-child(2n-1) {
    font-weight: bold;
    font-size: 30px;
}

짝수번째 형제 요소 선택

css code

#test1 > p:nth-child(2n) {
    border: 3px solid black;
}

형태 구조 선택자

선택된 형제 관계 요소 중 특정 요소를 선택하는 선택자 (선택된 요소들을 기준으로 구분)

:first-of-type

같이 선택된 형제들 중에서 첫번째 요소

:last-of-type

같이 선택된 형제들 중에서 마지막 요소

:nth-of-type(수열)

같이 선택된 형제들 중에서 수열번째 모든요소

:nth-last-of-type(수열)

같이 선택된 형제들 중에서 뒤에서 수열번째 모든요소

해석 순서 : 지정한 태그 중 n번째

html code

<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>

css code

#test2 > p:first-of-type {
    background-color: orange;
}

#test2 > p:last-of-type {
    background-color: skyblue;
}

#test2 > p:nth-of-type(2n-1) {
    font-size: 30px;
}

#test2 > p:nth-last-of-type(2n) {
    background-color: plum;
}

부정 선택자

( 선택자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>

css code

#test3 > li:not(:nth-of-type(3n)) {
    background-color: aquamarine;
}

#test3 자식 li 요소 중 3의 배수를 제외한 요소만 선택

0개의 댓글