0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Sass】カスタム名称で値を簡略化する方法。@functionとmap-getモジュールの処理内容

Posted at

Sassの変数、@function、build-in(組み込み)モジュールであるmap-getを使うと、プロパティの値を自由に変更することができる。

例えば、カラーコードのように覚えにくい値に好きな名称をつけ、その名称で値を設定できる。

.scss
/* map-getモジュールで設定 */
$colors: (
    default-text: #333,
    myblue-default: #1684c4,
    myblue-light: #1e97dd,
    myblue-super-light: #89d4ff,
    myblue-dark: #0d5d8b,
    myblue-super-dark: #083e5e,
);
@function colors($key) {
    @return map-get($colors, $key);
}

/* プロパティの設定 */
.hoge{
  color: colors(myblue-default);
}

値に自分で作成した変数(&キー)を使用。

 ↓ cssにコンパイル

.css
.hoge {
  color: #1684c4;
}

選択した色が適用されている。


## 処理の中身を確認 パッと見ややこしいけど、処理の中身を一つづつ追えば割と簡単。

1. 変数の定義

.scss
$colors: (
    myblue-default: #1684c4,
    myblue-light: #1e97dd,
    myblue-super-light: #89d4ff,
    myblue-dark: #0d5d8b,
    myblue-super-dark: #083e5e,
);

まずは、$colorsという変数を作成し、中にKV(キーと値)でカスタム名とカラーコードを記述している。

2. 関数の定義

.scss
@function colors($key) {
    @return map-get($colors, $key);
}

@functionを使って関数を定義する。

@returnで戻り値として、map-get($colors, $key)を指定。

map-get($変数名, キー名)
map-getを使うと、第1引数で指定した変数の中から、第2引数で指定したキー名に該当する値を取得してくる。

3. 値の取得

.scss
.hoge{
  color: colors(myblue-default);
}

colors(myblue-default)
colors関数に引数myblue-defaultを渡している。

上記No.2の関数が実行され、map-get($colors, myblue-default)により myblue-default: #1684c4,の値が取得される。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?