때때로 우리는 CSS를 생성할 때 특정 요소를 대상으로 삼고 싶을 때가 있습니다. <div>로 가득 찬 HTML 문서가 있다고 가정해 봅시다. 태그 및 <span> 태그가 있지만 어떤 방식으로든 스타일을 지정하기 위해 각 유형의 첫 번째 유형만 대상으로 하고 싶었습니다. :first-of-type 의사 클래스라고 하는 것으로 그렇게 할 수 있습니다.
의사 클래스는 CSS 선택자가 주어진 원래 스타일과 다른 특정 스타일을 갖도록 하는 방법입니다. 이것은 요소의 상태에 따라 다릅니다. 이 경우 첫 번째 <div>를 선택하려고 합니다. 첫 번째 <span> 스타일을 지정할 수 있습니다. 다른 범위나 div는 선택되지 않습니다.
다음은 시작하기 위한 예입니다.
<html>
<head>
<style>
body {
display: flex;
flex-flow: row wrap;
}
div {
height: 100px;
width: 200px;
border: 1px solid black;
margin: 20px;
padding: 20px;
}
/* First of type */
div:first-of-type {
background: purple;
color: white;
}
div span:first-of-type {
color: red;
text-decoration: underline;
background: lightblue;
}
</style>
</head>
<body>
<div>I am the first div<span> I am inside the div and the first span</span><span> I am the second span</span></div>
<div>I am the second the div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the third div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the fourth div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the fifth div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the sixth div<span> I am inside the div</span><span> I am the second span</span></div>
<div>I am the seventh div<span> I am inside the div</span><span> I am the second span</span></div>
</body>
</html>
여기에 div 안에 div와 span 세트가 있습니다. CSS 선택기 div:first-of-type 해당 유형의 맨 처음 요소만 선택하고 스타일을 지정합니다. div span:first-of-type div가 부모 요소이므로 각 div의 첫 번째 범위를 선택합니다.
div:first-of-type div:nth-child(1) 라고 말하는 것과 같습니다.
결론
이 기사에서 우리는 :first-of-type 의사 클래스를 살펴보았습니다. 우리는 의사 클래스가 기본적으로 우리가 스타일을 지정할 때 CSS 선택기가 있기를 원하는 상태를 설명하는 것임을 보았습니다. 또한 일반 구문도 살펴보았습니다. 나는 다른 의사 선택자를 살펴보고 그들에 대한 느낌도 얻을 것을 제안합니다!