@each
는 list
와 map데이터
를 반복할 때 사용한다.
자바스크립트
for in 반복문
과 유사하다.
하나의 데이터를 저장하기 위해서 변수
를 사용하는데, 여러 개의 데이터를 저장할 때에는 list
또는 map
이라는 형식으로 저장한다.
연관된 데이터들끼리 모아서 하나의 변수에 저장하여 편하게 관리하기가 쉽다.
//@each 문법에 하나의 변수만 사용할 때 문법
@each $변수 in 리스트 또는 맵 데이터 {
/* 반복 내용 */
}
/* 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');
}
/* 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");
}
/* 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;}
사용 목적과 방법은 list
와 유사하다.
특징은 각 값마다 매칭된 키가 있기 때문에 동적으로 접근할 수 있다.
또한 css
에는 없는 sass
의 고유 문법이며, 많은 양의 데이터를 컨트롤하기 위해서 반드시 필요하다.
/* 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');}
@while
은 조건이 false
를 반환할 때까지 내용을 반복하며 자바스크립트의 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;}