조건문

김동현·2021년 11월 22일
0
post-thumbnail

@if

@if 지시어는 조건에 따른 분기 처리가 가능하며, if 문과 유사합니다. 같이 사용할 수 있는 지시어는 @else, @else if가 있습니다. 추가 지시어를 사용하면 조금 더 복잡한 조건문을 작성할 수 있습니다.

// 1. @if
@if (조건) {
    /* 조건이 참인 경우*/
}

// 2. @if , @else
@if (조건) {
    /* 조건이 참인 경우 */
} @else {
    /* 조건이 거짓인 경우 */
}

//3. @if, @else if, @else
@if (조건1) {
    /* 조건1이 참인 경우 */
} @else if (조건2) {
    /* 조건2가 참인 경우 */
} @else {
    /* 조건1, 조건2가 거짓인 경우 */
}

조건에 ( )은 생략이 가능하기 때문에 ( ) 없이 작성하는 방법이 조금 더 편리할 수 있습니다.

$bg: true;

div {
    @if $bg {
        background-image: url('images/a.jpg');
    }
}

// SCSS
$color: orange;

div {
    @if ($color == strawberry) {
        color: #FE2E2E;
    } @else if ($color == orange) {
        color: #FE9AZE;
    } @else {
        color: #2A1B0A;
    }
}

// CSS
div {
    color: #FE9AZE;
}

그리고 논리 연산자인 and, or, not도 사용할 수 있습니다.

// SCSS
@mixin limitSize($size) {
    @if ($size >= 0 and $size < 500px) {
        width: 300px;
    } @else {
        width: 600px;
    }
}

div {
    @include limitSize(200px);
}

// CSS
div {
    width: 200px;
}

// SCSS
@mixin positionCenter($w, $h, $p: absolute) {
    @if not ($p == static or $p == relative) {
    
        width: if(unitless($w), #{$w}px, $w);
        heigth: if(unitless($h), #{$h}px, $h);
        
        position: $p;
        
        top: 0;
        botton: 0;
        right: 0;
        left: 0;
        
        margin: auto;
    }
}

.box {
    @include positionCenter(10, 10);
}

.box2 {
    @include positionCenter(10, 10, static);
}

.box3 {
    @include positionCenter(10, 10, relative);
}

// CSS
.box {
    width: 10px;
    height: 10px;
    position: absolute;
    top: 0;
    bottom: 0;
    rigth: 0;
    left: 0;
    margin: auto;
}

위 코드에서 unitless()라는 내장 함수를 사용하면 전달된 인수가 단위가 없다면 true, 있다면 false를 반환합니다. 이를 이용하여 if 함수로 만약 값에 단위가 없다면 px라는 단위를 붙이도록 하였습니다.

그리고 not 연산자와 and 연산자를 통해 $p에 static이나 relative가 전달되는 경우에는 사용되지 않도록 정의하였습니다.

profile
Frontend Dev

0개의 댓글