[scss] @each, @while

홍싸리·2023년 5월 22일
0

scss

목록 보기
2/4

1. @each

@eachlistmap데이터를 반복할 때 사용한다.

자바스크립트 for in 반복문과 유사하다.

list

하나의 데이터를 저장하기 위해서 변수를 사용하는데, 여러 개의 데이터를 저장할 때에는 list 또는 map이라는 형식으로 저장한다.
연관된 데이터들끼리 모아서 하나의 변수에 저장하여 편하게 관리하기가 쉽다.

//@each 문법에 하나의 변수만 사용할 때 문법
@each $변수 in 리스트 또는 맵 데이터 {
	/* 반복 내용 */
}

@each list data반복문

/* SCSS */
$fruits: (apple, banana, mango, orange);

.list-fruits{
	@each $fruit in $fruits{
    	li.#{$fruit} {
        	background: url('../img/#{$fruit}.png');
        }
    }
}

/* CSS 컴파일 결과 */
.list_fruits li.apple{
	background: url('../img/apple.png');
}
.list_fruits li.banana{
	background: url('../img/banana.png');
}
.list_fruits li.mango{
	background: url('../img/mango.png');
}
.list_fruits li.orange{
	background: url('../img/orange.png');
}

@each 반복문에 두 개 이상의 변수 사용

/* SCSS */
//첫번째 방법
.list-fruits{
	@each $fruit in apple, banana, mango, orange{
    	li.#{fruit} {
        	background: url('../img/#{$fruit}.png');
        }
    }
}

//두번째 방법
$fruits: apple, banana, mango, orange;
.list-fruits{
	@each $fruit in $fruits{
    	li.#{fruit} {
        	background: url('../img/#{$fruit}.png');
        }
    }
}


/* CSS 컴파일 결과
   두 가지 경우 모두 동일하게 나옴 */
.list_fruits li.apple {
  background: url("../img/apple.png");
}
.list_fruits li.banana {
  background: url("../img/banana.png");
}
.list_fruits li.mango {
  background: url("../img/mango.png");
}
.list_fruits li.orange {
  background: url("../img/orange.png");
}

@each index값이 필요한 경우

/* SCSS */
$fruits: (apple, banana, mango, orange);

.list-fruits{
	@each $fruit in fruits {
    	$i: index($fruits, $fruit);
        li:nth-of-type(#{$i}){
        	left: 100px * $i;
        }
    }
}

/* CSS 컴파일 결과 */
.list-fruits li:nth-of-type(1){left:100px;}
.list-fruits li:nth-of-type(2){left:200px;}
.list-fruits li:nth-of-type(3){left:300px;}
.list-fruits li:nth-of-type(4){left:400px;}

map

사용 목적과 방법은 list와 유사하다.
특징은 각 값마다 매칭된 키가 있기 때문에 동적으로 접근할 수 있다.
또한 css에는 없는 sass의 고유 문법이며, 많은 양의 데이터를 컨트롤하기 위해서 반드시 필요하다.

@each Map Data

/* SCSS */
$coffees: (mild: americano, soft: latte, strong: espresso, sweet: mocha);

@each $state, $menu in $coffees{
	.#{$state}-icon {
    	background: url('../img/#{$menu}.png');
    }
}

/* CSS 컴파일 결과 */
.mild-icon{background:url('../img/americano.png');}
.soft-icon{background:url('../img/latte.png');}
.strong-icon{background:url('../img/espresso.png');}
.sweet-icon{background:url('../img/mocha.png');}

2. @while

@while은 조건이 false를 반환할 때까지 내용을 반복하며 자바스크립트의 while문과 유사하다.

잘못된 조건으로 인해 컴파일 중 무한 루프에 빠질 수 있기에 사용을 권장하지 않는다.

@while 조건 {
	//반복 내용
}

@while 문법 코드

/* SCSS */
$i: 6;

@while $i > 0{
	.list-#{$i} {
    	width: 2px * $i;
    }
    $i: $i - 2;
}

/* CSS 컴파일 결과 */
.list-6 {width:12px;}
.list-4 {width:8px;}
.list-2 {width:4px;}
profile
그럴싸한건 다 따라해보는 프론트엔드 개발자 준비중인 6년차 퍼블리셔

0개의 댓글