@each
는 List와 Map 데이터를 반복할 때 사용한다.
for in문과 유사하다.
@each $변수 in 데이터 {
// 반복 내용
}
List 데이터를 반복해보자.
SCSS
// List Data
$fruits: (apple, orange, banana, mango);
.fruits {
@each $fruit in $fruits {
li.#{fruit} {
background: url("/images/#{$fruit}.png")
}
}
}
⬇️
CSS
.fruits li.apple {
background: url("/images/apple.png")
}
.fruits li.orange {
background: url("/images/orange.png")
}
.fruits li.banana {
background: url("/images/banana.png")
}
.fruits li.mango {
background: url("/images/mango.png")
}
매번 반복마다 Index값이 필요하다면, 다음과 같이 index()
내장 함수를 사용할 수 있다.
SCSS
$fruits: (apple, orange, banana, mango);
.fruits {
@each $fruit in $fruits {
$i: index($fruits, $fruit);
li:nth-child(#{$i}) {
left: 50px * $i;
}
}
}
⬇️
CSS
.fruits li:nth-child(1) {
left: 50px;
}
.fruits li:nth-child(2) {
left: 100px
}
.fruits li:nth-child(3) {
left: 150px;
}
.fruits li:nth-child(4) {
left: 200px;
}
동시에 여러 개의 List 데이터를 반복 처리할 수도 있다.
단, 각 데이터의 Length가 같아야 한다.
SCSS
$apple: (apple, korea);
$banana: (banana, japan);
$orange: (orange, china);
@each $fruit, $country in $apple, $banana, $orange {
.box-#{$fruit} {
background: url("/images/#{$country}.png")
}
}
⬇️
CSS
.box-apple {
background: url("/images/korea.png");
}
.box-banana {
background: url("/images/japan.png");
}
.box-orange {
background: url("/images/china.png");
}
Map 데이터를 반복할 경우 하나의 데이터에 두 개의 변수가 필요하다.
@each $key변수, $value변수 in 데이터 {
// 반복 내용
}
SCSS
$fruits-data: (
apple: korea,
banana: japan,
orange: china
);
@each $fruit, $counrty in $fruits-data {
.box-#{$fruits} {
background: url("/images/#{$country}.png")
}
}
⬇️
CSS
.box-apple {
background: url("/images/korea.png")
}
.box-japan {
background: url("/images/japan.png")
}
.box-china {
background: url("/images/china.png")
}