2. CSS

CSS nth-child() 사용하기 (even, odd, 3n+1)

도피디 2024. 11. 28. 00:03
반응형

 

기본 코딩

<!DOCTYPE html>
<html lang="kr">
<head>
<title>The Nick Times</title>
<style>
body {
height: 1000vh;
margin: 50px;
}
span {
background-color: aquamarine;
}
</style>
</head>
<body>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
</body>
</html>

 

 

결과


여기서 두번째, 네번째 span의 배경색을 다른 색으로 바꿔보자!

<!DOCTYPE html>
<html lang="kr">
<head>
<title>The Nick Times</title>
<style>
body {
height: 1000vh;
margin: 50px;
}
span {
background-color: aquamarine;
}
span:nth-child(2),
span:nth-child(4) {
background-color: yellow;
}
</style>
</head>
<body>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
</body>
</html>

 

 

결과

 

 


 

even(짝수 2,4,6,8,10...)를 사용해서 span 색깔을 번갈아 가면서 적용시키기

<!DOCTYPE html>
<html lang="kr">
<head>
<title>The Nick Times</title>
<style>
body {
height: 1000vh;
margin: 50px;
}
span {
background-color: aquamarine;
}
span:nth-child(even) {
background-color: yellow;
}
</style>
</head>
<body>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
<span>hello</span>
</body>
</html>

 

 

 

결과

짝수 순서에만 노란색이 적용됨 (2, 4, 6, 8, 10번째)

 

 

 

홀수는 odd를 넣어주면 된다.


nth-child(3n+1)

을 넣어주면 3의 배수 순서에 적용된다

 

 

 

결과

 

반응형