scss で 変数を使う

LastModified
Category SCSS

概要

変数と配列の使用方法

参考

https://sass-lang.com/documentation

変数を定義する

SCSS


$color: #333;

#scss01{
    color: $color;
}

CSSコンパイル後


#scss01{
    color: #333;
}

classに変数をつかう

SCSS


$name: hoge;

.bg-#{$name}{
    background-color: #000;
}

CSSコンパイル後


.bg-hoge{
    background-color: #000;
}

配列 (list)

SCSS


$colors: azure, lightskyblue, mediumaquamarine;

@each $color in $colors {
    .bg-#{$color}{
        background-color: $color;
    }
}

CSSコンパイル後


.bg-azure {
    background-color: azure
}

.bg-lightskyblue {
    background-color: #87cefa
}

.bg-mediumaquamarine {
    background-color: #66cdaa
}

プレビュー

azure
lightskyblue
mediumaquamarine

<div class="bg-azure">azure</div>
<div class="bg-lightskyblue">lightskyblue</div>
<div class="bg-mediumaquamarine">mediumaquamarine</div>

連想配列 (map)

SCSS


$colors: (
    default: #efefef,
    primary: #00d1b2,
    success: #48c774,
    danger: #f14668,
);

a.btn {
    background-color: map-get($colors, 'default');
    color: #333;
}

@each $key,$color in $colors {
    a.btn {
        &.#{$key}{
            background-color: $color;
        }
    }
}

CSSコンパイル後


a.btn {
    background-color: #efefef;
    color: #333;
}

a.btn.default {
    background-color: #efefef
}

a.btn.primary {
    background-color: #00d1b2
}

a.btn.success {
    background-color: #48c774
}

a.btn.danger {
    background-color: #f14668
}

プレビュー


<a class="btn">none</a>
<a class="btn default">default</a>
<a class="btn primary">primary</a>
<a class="btn success">success</a>
<a class="btn danger">danger</a>

多重配列

SCSS


$colors: (
    default:(
        bgc: #efefef,
        color: #333
    ),
    primary: (
        bgc: #00d1b2,
        color: #fff
    ),
    success: (
        bgc: #48c774,
        color: #fff
    ),
    danger: (
        bgc: #f14668,
        color: #fff
    ),
);

span.label {
    background-color: map-get(map-get($colors, 'default'), 'bgc');
    color: map-get(map-get($colors, 'default'), 'color');
    display: inline-block;
    padding: 0.2em 0.6em;
}

span.label {
    @each $key,$color in $colors {
        &.#{$key} {
            background-color: map-get($color, 'bgc');
            color: map-get($color, 'color');
        }
    }
}

CSSコンパイル後


span.label {
    background-color: #efefef;
    color: #333;
    display: inline-block;
    padding: 0.2em 0.6em;
}

span.label.default {
    background-color: #efefef;
    color: #333
}

span.label.primary {
    background-color: #00d1b2;
    color: #fff
}

span.label.success {
    background-color: #48c774;
    color: #fff
}

span.label.danger {
    background-color: #f14668;
    color: #fff
}

プレビュー

none default primary success danger

<span class="label">none</span>
<span class="label default">default</span>
<span class="label primary">primary</span>
<span class="label success">success</span>
<span class="label danger">danger</span>