SCSS 조건문 (@if, @for)

·2026년 2월 24일

코딩

목록 보기
48/48

SCSS 조건문 - @if문

: @if, @else if, @else 사용 (JS와 유사)

  1. 조건문 작성
@mixin breakpoint-view($breakpoint) {
	@if $breakpoint == pc {
		@media (width >= 1280px) {
			@content;
		}
	} @else if $breakpoint == tablet {
		@media (width <= 920px) {
			@content;
		}
	} @else {
		@media (width <= 480px) {
			@content;
		}
	}
}

-> 매개변수 만들어서 조건문 사용
@content : 콘텐츠 그대로 가져옴

  1. @include 하고 content 작성
.con {
		@include breakpoint-view(tablet) {
			padding-inline: 1rem;
		}
	}

-> width값이 tablet 조건문이 되면 .con의 padding 좌우값이 1rem이 된다


SCSS 조건문 - @for문

: @for 사용

  • @for $i from 1 through 7 { } ( 1부터 7까지 포함 )
  1. @for문 작성 &-#{$i} { ~ }
.section-1 {
	.box {
		@for $i from 1 through 7 {
			&-#{$i} {
				background-color: nth((red, orange, yellow, green, blue, navy, purple), $i);
			}
		}
	}
}
  1. 리스트(배열) 사용 - 더 깔끔함
.section-1 {
	// 리스트
	$colors: (red, orange, yellow, green, blue, navy, purple);
	.box {
		@for $i from 1 through 7 {
			&-#{$i} {
				background-color: nth(($colors), $i);
			}
		}
	}
}

-> $colors를 만들어서 nth(()) 안에 넣어주기

  • @for $i from 1 to 7 { } ( 1부터 7까지 / 1~6만 나옴. 7은 제외)

여러가지 이미지를 불러와야할 때 꿀팁 ( 단 id가 있는 사진이어야함 )
.box {
		@for $i from 1 through 7 {
			&-#{$i} {
				background-image: url(https://picsum.photos/id/#{$i}/200/300)
			}
		}
	}

lorem picsum에서 id 있는 링크 불러오기
id 옆 번호에 #{$i}로 해서 다양한 이미지 불러오기 가능

0개의 댓글