条件分岐

条件に応じて分岐処理を行うことができます。
条件分岐の方法は2種類あり@if文またはif関数を使用します。
@ifを使用する場合、他の条件を追加する場合は@else if文、何れも一致しない場合は@else文を使用することができます。

構文

@if文

							@ifのみの場合
							@if 条件文 {
    真の内容
}
@if + @elseの場合 @if 条件文 {
    真の内容
} @else {
    否の内容
}
@if + @else if + @elseの場合 @if 条件文 {
    真の内容
} @else if 条件文 {
    真の内容
} @else {
    否の内容
}

if関数

							if(条件式, 真の内容, 否の内容)
						

対応SASSバージョン:@if = 2.2.0+
対応SASSバージョン:@if + @else = 2.2.0+
対応SASSバージョン:@if + @else if + @else = 2.2.0+

サンプルコード

@if文

SCSS

$category:products;
 
.sample {
    @if $category == products {
        width:700px;
    } @else if $category == company {
        width:900px;
    } @else {
        width:100%;
    }
}

コンパイル後:CSS

.sample {
    width:700px;
}

if関数

SCSS

$category:products;
 
.sample {
    width:if($category == products, 700px, 900px);
}

コンパイル後:CSS

.sample {
    width:700px;
}

次のようにセレクターで使用することもできます。

SCSS

@for $n from 1 through 3 {
    .sample#{if($n == 1, ":first-of-type", ":nth-of-type(#{$n})")} {
        grid-row:$n;
    }
}

コンパイル後:CSS

.sample:first-of-type {
    grid-row:1;
}
 
.sample:nth-of-type(2) {
    grid-row:2;
}
 
.sample:nth-of-type(3) {
    grid-row:3;
}

SASS・SCSS逆引きリファレンス一覧へ戻る