본문 바로가기
Style Sheets/Sass(SCSS)

[SCSS] 조건문 (@if / @else if / @else)

by 썸머워즈 2022. 6. 25.
반응형

@if

흔히 알고 있는 if문으로 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);
}

to css

.square-av {
  width: 100px;
  height: 100px;
}

.circle-av {
  width: 100px;
  height: 100px;
  border-radius: 50px;
}

 

그리고 추가적으로 삼항 연산자 역시 사용할 수 있는데,

if(조건, 표현식1, 표현식2)

조건이 true이면 표현식1을 false이면 표현식2를 실행하는 방식으로 삼항연산자와 비슷하게 사용할 수 있다.

$width: 555px;
div {
  width: if($width > 300px, $width, null);
}

to css

div {
  width: 555px;
}

@ else if ~ else

@if와 함께 @else if 와 @else 역시 사용이 가능하다.

@use "sass:math";

@mixin triangle($size, $color, $direction) {
  height: 0;
  width: 0;

  border-color: transparent;
  border-style: solid;
  border-width: math.div($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);
}

to css

.next {
  height: 0;
  width: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 2.5px;
  border-left-color: black;
}

참고: https://sass-lang.com/documentation/at-rules/control/if

 

Sass: @if and @else

The @if rule is written @if { ... } , and it controls whether or not its block gets evaluated (including emitting any styles as CSS). The expression usually returns either true or false—if the expression returns true, the block is evaluated, and if the e

sass-lang.com

참고: https://heropy.blog/2018/01/31/sass/

 

Sass(SCSS) 완전 정복!

Style(CSS) 작업 시 필수가 되어버린 CSS Preprocessor(전처리기) Sass(SCSS)에 대해서 이해하고, CSS로 컴파일하는 방법부터 자세한 SCSS 문법까지 살펴봅니다.

heropy.blog

반응형


댓글

TOP