본문 바로가기
WWWEB/CSS

[CSS] ":nth-child()"로 몇 번부터 몇 번까지 선택하기

by 미니토이 2023. 8. 21.

 

위 그림처럼 기획에서 평소에 잘 보지 못한 디자인을 요청해옴~

 

해당 요소에 평범하게 클래스를 주고 스타일을 입히는 것이 일반적인 방법이었으나,

nth-child로 몇 번부터 몇 번까지 선택하는 방법을 사용함.

 

해당 기획은 테이블이 아닌 클릭하는 <button> 요소라

위 마크업처럼 <div> 안에 버튼들로 100개를 채워줌~

 

<div class="button-list">
    <button type="button">...</button>
    <button type="button">...</button>
    <button type="button">...</button>
    .
    .
    .
    <button type="button">...</button>
</div>

 

 

디자인은 41번부터 45번까지 컬러를 입혀야 하기 때문에,
:nth-child()로 간단하게 해주면 끝~~~

 

.button-list :nth-child(n+41):nth-child(-n+45){
    background: #79d6df;
}

 

 

 

 

알아두면 좋은 선택 예시

/* n번 단일 선택 */
.selector:nth-child(n){
    background: pink;
}

/* 뒤에서 n번째 선택 */
.selector:nth-last-child(n){
    background: pink;
}

/* 2n번째 선택 */
.selector:nth-child(2n){
    background: pink;
}

/* 홀수 선택 */
.selector:nth-child(odd){
    background: pink;
}

/* 짝수 선택 */
.selector:nth-child(even){
    background: pink;
}

/* 1번부터 5번까지 선택 */
.selector:nth-child(-n+5){
    background: pink;
}

/* 5번부터 모두 선택하기 */
.selector:nth-child(n+5){
    background: pink;
}

/* 뒤에서 1번부터 5번까지 선택 */
.selector:nth-last-child(-n+5){
    background: pink;
}

/* 뒤에서 5번부터 모두 선택 */
.selector:nth-last-child(n+5){
    background: pink;
}

/* 5번~10번 선택 */
.selector:nth-child(n+5):nth-child(-n+10){
    background: pink;
}

 

 

728x90
반응형

댓글