CSS selector, nth-child()와 nth-of-type() 비교

카테고리 IT/코딩 CSS

무찌마, 댓글

초고 2022. 3. 19.

CSS selector

div:nth-child(3)

 

하나의 부모 container에 들어 있는 자식들 중 3번째 자식이 <div>이면 CSS 적용시키고, 만약 <P>와 같은 다른 요소이면 이 규칙은 적용되지 않습니다. 요약하면, 

- 유형(type) 상관 없이 부모 객체의 3번째 자식 객체를 찾아서

- 앞에 지정한 요소(div)와 동일한 유형(div)의 자식일 경우에만 CSS 적용


div:nth-of-type(3)

 

하나의 부모 container에 들어 있는 자식들 중 <div>만 선택 대상에 포함하여 그들 중 3번째 자식에게 CSS 적용

- 부모 객체의 <div> 유형(type) 자식들만 찾아서

- 그것들(div) 중 3 번째 자식에게 CSS 적용


부모 container에 child가 1개만 있을 때

 

1. first-child와 last-child가 동일한 CSS 속성을 지정할 경우

div:first-child {
	background-color: white;
}
div:last-child {
	background-color: black;
}

동일한 div child 객체를 first-child로 먼저 설정한 background-color 값을, 나중에 지정한 last-child의 background-color 값으로 대체합니다.

div {
	background-color: black;
}

 

2. first-child와 last-child가 다른 CSS 속성을 지정할 경우

div:first-child {
	margin-left: 50px;
}

 

div:last-child {
	margin-right: 50px;
}

 

동일한 div child 객체를 first-child로 먼저 CSS 설정하고, 나중에 last-child로 CSS 추가하였지만, 각각 지정한 속성이 margin-left와 margin-right로 다릅니다. 이럴 경우에는 대체되지 않고 합쳐집니다.

div {
	margin-left: 50px;
	margin-right: 50px;
}

 

댓글