🐔

6. 조건문과 반복문, 함수

1. 조건문

조건에 따라 스타일을 주고자 할 때, if와 else문을 사용하는데요. if문 하나만 사용하는 경우도 있으며, 뒤에 나오는 else문, else if문과도 함께 사용하는 경우도 있습니다.
 

1-1. @if

@if에 괄호 없이 true나 false를 반환할 수 있는 조건문을 작성하시면 됩니다. (조건을 작성할 때 괄호를 사용할 수 있지만 일반적으로 괄호는 생략합니다) 조건에는 논리연산자 and, or, not을 사용하고, if문의 조건이 true일 때만 { } 괄호 안에 있는 코드가 실행됩니다.
@if (조건) { // 조건이 참일 때 실행될 구문 }
 
// if문 예시 작성 // Sass 공식문서 // circle이 false면 사각형을, true이면 원형으로 스타일함 @mixin avatar($size, $circle: false) { width: $size; height: $size; @if $circle { border-radius: $size / 2; } } .square-av { @include avatar(100px, $circle: false); } .circle-av { @include avatar(100px, $circle: true); }
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
 
/*CSS*/ .square-av { width: 100px; height: 100px; } .circle-av { width: 100px; height: 100px; border-radius: 50px; }
 

1-2. @else

@else문은 if 문처럼 조건문이 필요하지는 않으며 if문에서 걸었던 조건이 false가 나오면 else문의 코드가 실행됩니다
@if (조건) { // 조건이 참일 때 실행될 구문 } @else { // if문의 조건이 거짓일 때 실행될 구문 }
 
// Scss - else문 // Sass 공식문서 // ture이면 밝은 색을, false면 어두운 색을 스타일함 $light-background: #f2ece4; $light-text: #036; $dark-background: #6b717f; $dark-text: #d2e1dd; @mixin theme-colors($light-theme: true) { @if $light-theme { background-color: $light-background; color: $light-text; } @else { background-color: $dark-background; color: $dark-text; } } .banner { @include theme-colors($light-theme: true); body.dark & { @include theme-colors($light-theme: false); } }
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
 
/*CSS*/ .banner { background-color: #f2ece4; color: #036; } body.dark .banner { background-color: #6b717f; color: #d2e1dd; }

1-3. @else if

@else if문은 if문으로 부족할 때, 즉 여러 개의 조건문을 사용해야 할 때 사용합니다. @else if문에도 true나 false를 반환하는 조건문을 작성합니다. if문의 조건에서 false가 나왔을 때, else if문으로 넘어가서 조건에 대해 true인지 false인지 판단합니다. true인 경우 else if문 내의 코드를 실행하고, false 라면 그 다음 조건문( else or else if )로 넘어가게 됩니다.
if (조건){ // 조건이 참일 때 실행될 구문 } @else if(조건){ // else if 조건이 참일 때 실행될 구문 } @else{ // 위에 모든 조건이 거짓일 때 실행될 구문 }
 
// Scss - if, else if, else문 // Sass 공식문서 // 조건에 해당하는 방향에 맞춰서 border-bottom 컬러를 스타일함 @mixin triangle($size, $color, $direction) { height: 0; width: 0; //여기 부분만 수정했습니다. border-color: black; border-style: solid; border-width: ($size/2); @if $direction == up { border-bottom-color: $color; } @else if $direction == right { border-left-color: $color; } @else if $direction == down { border-top-color: $color; } @else if $direction == left { border-right-color: $color; } @else { @error "Unknown direction #{$direction}."; } } .next { @include triangle(5px, black, right); }
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
 
 
/*CSS*/ .next { height: 0; width: 0; border-color: transparent; border-style: solid; border-width: 2.5px; border-left-color: black; }

2. 반복문

2-1. @for

for ($변수) from (시작) through(끝){ // 반복할 내용 }
@for은 정의한 횟수만큼 코드 실행을 반복합니다. @for문에 from(시작 : 이상) - through(끝 : 이하)를 사용하여 어디서 시작해서 어디서 끝날 지를 알려줍니다. nth- 선택자를 사용하는 경우 유용하게 사용할 수 있습니다.
 
// Scss - for문 // for문을 이용해 nth-선택자에게 각각의 image를 배경에 넣어준다. @for $hojun from 1 through 7 { .photo-box:nth-child(#{$hojun}) { background-image: url("../assets/phoster#{$hojun}.png"); } } // 범위 1이상 5이하 // for문에서 1부터 5까지 반복하라는 의미입니다. 총 5번 반복되면서 코드가 실행된다. // 만약 from 3 throught 8 이라면 3에서 8까지 6번 실행된다.
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
 
/*CSS*/ .photo-box:nth-child(1) { background-image: url("../assets/phoster1.png"); } .photo-box:nth-child(2) { background-image: url("../assets/phoster2.png"); } .photo-box:nth-child(3) { background-image: url("../assets/phoster3.png"); } .photo-box:nth-child(4) { background-image: url("../assets/phoster4.png"); } .photo-box:nth-child(5) { background-image: url("../assets/phoster5.png"); }
// .content-1 { // font-size: 10px; // width: 100px; // height: 100px; // background-color: red; // } // ... // .content-10 { // font-size: 100px; // width: 100px; // height: 100px; // background-color: red; // } @for $hojun from 1 through 10 { .content-#{$hojun} { font-size: #{$hojun * 10}px; width: 100px; height: 100px; background-color: red; } }

2-2. @each

each문은 lists나 맵의 각각의 요소마다 코드를 실행해서 스타일을 적용할 수 있게 합니다.
@each ($변수) in (리스트나 맵){ // 반복할 내용 }
 
// Sass - each문 // color-palette 리스트에 들어있는 색상을 each문을 사용하여 background에 색상값을 넣어준다. $color-palette: #dad5d2 #3a3532 #375945 #5b8767 #a6c198 #dbdfc8; @each $color in $color-palette { $i: index($color-palette, $color); //index는 list의 내장함수 .color-circle:nth-child(#{$i}) { background: $color; width: 20px; height: 20px; border-radius: 50%; } }
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
notion imagenotion image
 
/*CSS*/ .color-circle:nth-child(1) { background: #dad5d2; width: 20px; height: 20px; border-radius: 50%; } .color-circle:nth-child(2) { background: #3a3532; width: 20px; height: 20px; border-radius: 50%; } .color-circle:nth-child(3) { background: #375945; width: 20px; height: 20px; border-radius: 50%; } .color-circle:nth-child(4) { background: #5b8767; width: 20px; height: 20px; border-radius: 50%; } .color-circle:nth-child(5) { background: #a6c198; width: 20px; height: 20px; border-radius: 50%; } .color-circle:nth-child(6) { background: #dbdfc8; width: 20px; height: 20px; border-radius: 50%; }
 

2-3. @while

@while 조건 { // 반복할 내용 }
특정 조건에 충족될 때까지 코드를 무한 반복하며, 조건을 만날 때 while문을 빠져나오게 됩니다. 참고로, while문은 빠져나오는 조건을 만드는 경우가 거의 없어서 잘 사용하지 않습니다.
// Scss - while문 // Sass 공식문서 // value값이 base보다 작을 때까지 일정한 값으로 계속 나눠준다. @function scale-below($value, $base, $ratio: 1.618) { @while $value > $base { $value: ($value/$ratio); } @return $value; } $normal-font-size: 16px; .sup { font-size: scale-below(20px, 16px); }
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
 
/*CSS*/ .sup { font-size: 12.36094px; }
 
 

3. function

3-1. function

@function 키워드를 사용하여 함수를 생성하고 함수이름( ) 형태로 함수를 호출하고 실행합니다. 함수 안에서는 @return 이용해 값을 반환합니다. 함수는 Mixin과 비슷하지만 mixin은 스타일 코드를 반환하고 function은 @return 키워드를 사용해서 값 자체를 반환한다는 차이가 있습니다.
@function 함수이름($매개변수) { // 실행 코드 @return 값 }
// Scss - function // Sass 공식문서 // 거듭제곱을 구하는 함수 @function pow($base, $exponent) { $result: 1; @for $_ from 1 through $exponent { $result: $result * $base; } @return $result; } .sidebar { float: left; margin-left: pow(4, 3) * 1px; }
※ Scss 파일 코드를 작성하여 실행한 후, css와 비교해 보세요!
 
/*CSS*/ .sidebar { float: left; margin-left: 64px; }
 

3-2. 내장함수

Sass에는 기본적으로 내장되어 있는 함수가 있습니다. 앞에서 lists와 maps를 설명하면서 관련 내장함수를 잠깐 확인했는데요. 그 외에 내장함수 중 몇 개만 더 살펴보겠습니다.
 
1) 색상 함수
  • lighten(color, amount) : 기존 색상의 밝기를 높입니다.( 0%-100% 사이의 값 )
  • darken(color, amount) : 기존 색상의 밝기를 낮춥니다.( 0%-100% 사이의 값 )
  • mix(color1, color2, weight) : 2개의 색상을 섞어서 새로운 색상을 만듭니다.
 
2) 숫자 함수
  • max(number, ..) : 괄호에 넣은 값 중에 가장 큰 수를 반환합니다.
  • min(number, ..) : 괄호에 넣은 값 중에 가장 작은 수를 반환합니다.
  • parcentage(number) : 퍼센트로 숫자를 바꿔줍니다.
  • comparable(num1,num2) : 숫자1과 숫자2가 비교 가능한지 확인 후 true,false 값을 반환합니다.
 
3) 문자 함수
  • srt-insert(string,insert,index) : 문자열에 원하는 위치(index)에 문자를 넣은 후(insert), 새로운 문자열을 반환합니다.
  • str-index(string,substring) : 문자열에서 해당 문자의 index 값을 반환합니다.
  • to-upper-case(string) : 문자열 전부를 대문자로 바꿔줍니다.
  • to-lower-case(string) : 문자열 전부를 소문자로 바꿔줍니다.
 
4) 확인 함수
  • unit(number) : 숫자의 단위를 반환해 줍니다.
  • unitless(number) : 단위를 가지고 있는지 판단하여 true,false 값을 반환합니다.
  • variable-exists(name) : 변수가 현재 범위에 존재하는지 판단하여 true,false 값을 반환합니다. 이 함수의 인수는 $없이 사용합니다.