6
3

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.

CSS変数に色のHEX値を入れると rgba() が使えないので RGB値も変数にする

Last updated at Posted at 2021-01-23

css変数に色を格納する時はRGB値も入れればOKという話

下記の記述は意図した結果になりません。

--color_red: #f00;

.red{
  // rgba(#f00, 0.5) と書いたのと同じなので反映されない
  color: rgba(var(--color_red), 0.5);
}

下記は透明度50%の赤になります。

--rgb_red: 255, 0, 0;

.red{
  color: rgba(var(--rgb_red), 0.5);
}

root に色の変数を格納しよう

こんな感じに色の一覧を作っておきます。

$colors:(
  red:(
    base: #f00,
    light: #f33,
    dark: #c00
  ),
  blue:(
    base: #00f,
    light: #33f,
    dark: #00c
  )
);

:root に色の変数を書き出します。

@use "sass:color";

:root{
  @each $name, $color in $colors) {
    @each $type, $code in $color {
      @if $type == "base" {
        --root-color_#{""+$name}: #{$code};
        --root-rgb_#{""+$name}: #{color.red($code)}, #{color.green($code)}, #{color.blue($code)};
      } @else {
        --root-color_#{""+$name}-#{$type}: #{$code};
        --root-rgb_#{""+$name}-#{$type}: #{color.red($code)}, #{color.green($code)}, #{color.blue($code)};
      }
    }
  }
}

出力結果。

:root{
  --root-color_red: #f00;
  --root-rgb_red: 255, 0, 0;
  --root-color_red-light: #f33;
  --root-rgb_red-light: 255, 51, 51;
  /* ...省略 */
}

dart-sass での方法です。
lib-sass では使えません。

6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?