SCSS - 반복

이호현·2020년 7월 23일
0

SCSS

목록 보기
6/6

1. @for

@for 정의

through를 사용하는 방법이 있고, to를 사용하는 방법이 있다.

@for 변수 from 시작 through 종료{
}

@for 변수 from 시작 to 종료{
}

@for 사용

through는 뒤에 오는 숫자까지 반복

@for $i from 1 through 3{
    .test1:nth-child(#{$i}){
        width: 20px * $i;
    }
}

위 내용은 아래와 같다

.test1:nth-child(1) {
  width: 20px;
}

.test1:nth-child(2) {
  width: 40px;
}

.test1:nth-child(3) {
  width: 60px;
}

to 뒤에 오는 숫자의 바로 앞까지 반복

@for $i from 1 to 3{
    .test2:nth-child(#{$i}){
        width: 20px * $i;
    }
}

위 내용은 아래와 같다

.test2:nth-child(1) {
  width: 20px;
}

.test2:nth-child(2) {
  width: 40px;
}

2. @each

@each 정의

@each $변수 in 데이터{
}

@each 사용1 (list)

$animals: (dog, cat, bear);

.animals{
    @each $animal in $animals{
        li.#{$animal}{
            width: 100px;
            height: 100px;
        }
    }
}

위 내용은 아래와 같다.

.animals li.dog {
  width: 100px;
  height: 100px;
}
.animals li.cat {
  width: 100px;
  height: 100px;
}
.animals li.bear {
  width: 100px;
  height: 100px;
}

@each 사용2 (map)

$animals: (
    dog: white, 
    cat: black, 
    bear: red
);

.animals{
    @each $animal, $color in $animals{
        .test-#{$animal}{
            width: 100px;
            height: 100px;
            background: $color;
        }
    }
}

위 내용은 아래와 같다.

.animals .test-dog {
  width: 100px;
  height: 100px;
  background: white;
}
.animals .test-cat {
  width: 100px;
  height: 100px;
  background: black;
}
.animals .test-bear {
  width: 100px;
  height: 100px;
  background: red;
}

3. @while

@while 정의

@while 조건{
}
>

@while 사용

$i: 1;

@while $i < 4{
    .test-#{$i}{
        width: 10px * $i;
    }
    $i: $i + 1;
}

위 내용은 아래와 같다.

.test-1 {
  width: 10px;
}

.test-2 {
  width: 20px;
}

.test-3 {
  width: 30px;
}
profile
평생 개발자로 살고싶습니다

0개의 댓글