- 의사클래스( :nth-child(n) )
: 형제 사이에서의 순서에 따라 요소를 선택함.
: 밑에 형제태그가 다 동일해야 사용가능 (중간에 다른 요소 있으면 안됨.)
- 요소 선택자( p:nth-of-type(n) )
: p 타입 중에 n번째를 지정하게 됨
: 중간에 형제가 다른 요소가 끼어 있어도 사용 가능함. (태그 타입을 직접 지정하는 거여서)
🔶1.의사클래스( :nth-child(n) )
span:first-child {
background-color: tomato;
}
span:last-child {
background-color: tomato;
}
span:nth-child(2),
span:nth-child(4) {
background-color: tomato;
}
span:nth-child(even) {
background-color: tomato;
}
span:nth-child(odd) {
background-color: tomato;
}
- 3개씩 마다: 3[3*1] 6[3*2] 9[3*3] 마다
(처음엔 3*0=0인데, 0번째 요소는 없기때문에 3부터 시작됨.)
span:nth-child(3n) {
background-color: tomato;
}
![](https://velog.velcdn.com/images%2Fjhplus13%2Fpost%2Fe4c1911b-7197-4643-9679-c637e8f81d52%2Fimage.png)
- 3번째 이후로 : 3[0+3] 4[1+3] 5[2+3] 마다
span:nth-child(n + 3) {
background-color: tomato;
}
![](https://velog.velcdn.com/images%2Fjhplus13%2Fpost%2Ff0ccfb46-25bf-4314-9aae-da2b867ca490%2Fimage.png)
- 5씩마다 : 1[0+1] 6[5+1] 11[10+1]
span:nth-child(5n + 1) {
background-color: tomato;
}
![](https://velog.velcdn.com/images%2Fjhplus13%2Fpost%2F795e700e-e84c-4158-b6e6-9339a478a5be%2Fimage.png)
- n개씩 마다: 3씩마다 : 1[0+1] 4[3+1] 7[6+1] 10[9+1]
span:nth-child(3n + 1) {
background-color: tomato;
}
![](https://velog.velcdn.com/images%2Fjhplus13%2Fpost%2Ff4641d7e-2538-451c-904e-e70840c677d4%2Fimage.png)
🔶2.요소 선택자( :nth-of-type(n) )
<style>
dl dd:nth-of-type(2) {
background-color: yellowgreen;
}
dl dd:last-of-type {
background-color: yellowgreen;
}
</style>
</head>
<body>
<dl>
<dt>목록의 주제</dt>
<dd>1</dd>
<dd>2</dd>
<dd>3</dd>
<dd>4</dd>
</dl>
![](https://velog.velcdn.com/images%2Fjhplus13%2Fpost%2F2b665631-1182-4875-87b9-9efcd76ae009%2Fimage.png)