[SCSS] 반복문 @for, @each

문지은·2023년 8월 27일
0

SCSS

목록 보기
11/11
post-thumbnail

반복문 @for

  • 자바스크립트와 마찬가지로 반복문(@for)은 변수($변수)를 선언하고 시작(from)해서 종료(through)가 되기 전까지 반복할 표현식을 계속 반복적으로 출력
  • 변수 선언은 일반적으로 $i를 사용
@for $변수 from 시작 through 종료 {
	// 반복할 표현식
}

.frame 클래스 안에 있는 <div> 요소들의 너비(width)를 반복문을 사용하여 다르게 설정해보자.

index.html

<div class="frame">
  <div>item1</div>
  <div>item2</div>
  <div>item3</div>
  <div>item4</div>
  <div>item5</div>
  <div>item6</div>
  <div>item7</div>
  <div>item8</div>
  <div>item9</div>
</div>

style.scss

.frame div {
    border: 3px solid black;
    margin: 5px;
    padding: 5px;
}

@for $i from 1 through 9 {
    .frame div:nth-child(#{$i}) {
        width: 50px * $i;
    }
}

style.css

.frame div {
  border: 3px solid black;
  margin: 5px;
  padding: 5px;
}

.frame div:nth-child(1) {
  width: 50px;
}

.frame div:nth-child(2) {
  width: 100px;
}

.frame div:nth-child(3) {
  width: 150px;
}

.frame div:nth-child(4) {
  width: 200px;
}

.frame div:nth-child(5) {
  width: 250px;
}

.frame div:nth-child(6) {
  width: 300px;
}

.frame div:nth-child(7) {
  width: 350px;
}

.frame div:nth-child(8) {
  width: 400px;
}

.frame div:nth-child(9) {
  width: 450px;
}

반복문 @each

  • 자바스크립트와 마찬가지로 반복문(@each)은 자바스크립트의 배열(Array) 형태를 사용하는 것이 보통이다.
  • @each@for과 달리 시작과 종료가 반복문 안에 정해져 있지 않다.
@each $변수 in $변수 {
	// 반복할 표현식
}

반복문 @each를 사용하여 이미지 크기를 다르게 출력해보자.

index.html

<div class="frame">
  <img src="./img.png" class="img-30px">
  <img src="./img.png" class="img-60px">
  <img src="./img.png" class="img-90px">
  <img src="./img.png" class="img-120px">
</div>

style.scss

.frame div {
    border: 3px solid black;
    margin: 5px;
    padding: 5px;
}

$size: 30px, 60px, 90px, 120px;

@each $size in $size {
    .img-#{$size} {
        width: $size;
        height: $size;
    }
}

style.css

.frame div {
  border: 3px solid black;
  margin: 5px;
  padding: 5px;
}

.img-30px {
  width: 30px;
  height: 30px;
}

.img-60px {
  width: 60px;
  height: 60px;
}

.img-90px {
  width: 90px;
  height: 90px;
}

.img-120px {
  width: 120px;
  height: 120px;
}

profile
코드로 꿈을 펼치는 개발자의 이야기, 노력과 열정이 가득한 곳 🌈

0개의 댓글