프로그래밍/Sass

[Sass/SCSS] 조건문(if)

미냐님 2020. 3. 26. 23:36
728x90

if (함수)

if(조건, 표현식1, 표현식2)
  • SCSS:
$width: 555px;
div {
  width: if($width > 300px, $width, null);
}
  • Compiled to:
div {
  width: 555px;
}
  • 위와 같이 함수는 @include 같은 별도의 지시어 없이 사용하기 때문에 내가 지정한 함수와 내장 함수(Built-in Functions)의 이름이 충돌할 수 있습니다.
    따라서 내가 지정한 함수에는 별도의 접두어를 붙여주는 것이 좋습니다

@if (지시어)

  • @if 지시어는 조건에 따른 분기 처리가 가능하며, if 문(if statements)과 유사합니다.
  • 같이 사용할 수 있는 지시어는 @else, if가 있습니다.
// @if
@if (조건) {
  /* 조건이 참일 때 구문 */
}

// @if @else
@if (조건) {
  /* 조건이 참일 때 구문 */
} @else {
  /* 조건이 거짓일 때 구문 */
}

// @if @else if
@if (조건1) {
  /* 조건1이 참일 때 구문 */
} @else if (조건2) {
  /* 조건2가 참일 때 구문 */
} @else {
  /* 모두 거짓일 때 구문 */
}
  • 조건에 ()는 생략이 가능하기 때문에, () 없이 작성하는 방법이 좀 더 편리할 수 있습니다.
$bg: true;
div {
  @if $bg {
    background: url("/images/a.jpg");
  }
}
  • SCSS:
$color: orange;
div {
  @if $color == strawberry {
    color: #FE2E2E;
  } @else if $color == orange {
    color: #FE9A2E;
  } @else if $color == banana {
    color: #FFFF00;
  } @else {
    color: #2A1B0A;
  }
} 
  • Compiled to:
div {
  color: #FE9A2E;
}
  • 조건에는 논리 연산자 and, or, not을 사용할 수 있습니다.

  • SCSS:

@function limitSize($size) {
  @if $size >= 0 and $size <= 200px {
    @return 200px;
  } @else {
    @return 800px;
  }
}

div {
  width: limitSize(180px);
  height: limitSize(340px);
}
  • Compiled to:
div {
  width: 200px;
  height: 800px;
}
  • 좀 더 복잡하지만 실용적이게 사용 가능

  • Sass의 내장 함수 unitless()는 숫자에 단위가 있는지 여부를 반환합니다.

  • SCSS:

@mixin pCenter($w, $h, $p: absolute) {
  @if
    $p == absolute
    or $p == fixed
    or not $p == relative
    or not $p == static
  {
    width: if(unitless($w), #{$w}px, $w);
    height: if(unitless($h), #{$h}px, $h);
    position: $p;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
  }
}

.box1 {
  @include pCenter(10px, 20px);
}
.box2 {
  @include pCenter(50, 50, fixed);
}
.box3 {
  @include pCenter(100, 200, relative);
}
  • Compiled to:
.box1 {
  width: 10px;
  height: 20px;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

.box2 {
  width: 50px;
  height: 50px;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
728x90