1
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?

Sassでコントラスト比を計算しWCAGの達成基準かどうかチェックする

Posted at

Sassでコントラスト比を計算し、WCAGの達成基準かどうかをチェックする Mixin を作りました。

Dart Sass 1.79.3 以上で動作します。

@use 'sass:math';
@use 'sass:color';

// 相対輝度を計算する関数
@function calculate-luminance($color) {
  $r: math.div(color.channel($color, "red", $space: rgb), 255);
  $g: math.div(color.channel($color, "green", $space: rgb), 255);
  $b: math.div(color.channel($color, "blue", $space: rgb), 255);
  // 計算方法の参考: https://www.w3.org/TR/WCAG22/#dfn-relative-luminance
  $r: if($r < 0.04045, math.div($r, 12.92), math.pow(math.div(($r + 0.055), 1.055), 2.4));
  $g: if($g < 0.04045, math.div($g, 12.92), math.pow(math.div(($g + 0.055), 1.055), 2.4));
  $b: if($b < 0.04045, math.div($b, 12.92), math.pow(math.div(($b + 0.055), 1.055), 2.4));
  @return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
}

// コントラスト比を計算する関数
@function contrast-ratio($color1, $color2) {
  $l1: calculate-luminance($color1);
  $l2: calculate-luminance($color2);
  @if $l1 > $l2 {
    // 計算方法の参考: https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio
    @return floor-to-2decimals(math.div(($l1 + 0.05), ($l2 + 0.05)));
  } @else {
    @return floor-to-2decimals(math.div(($l2 + 0.05), ($l1 + 0.05)));
  }
}

// コントラスト比がWCAGの達成基準を満たしているかチェックする関数
@function success-criterion($contrast) {
    @if $contrast >= 7 { @return "AAA"; }
    @else if $contrast >= 4.5 { @return "AA";}
    @else if $contrast >= 3 { @return "AA (Large Text)"; }
    @else { @return "Fail"; }
}

// 小数点以下2桁で切り下げる関数
@function floor-to-2decimals($number) {
  $factor: 100;
  @return math.div(math.floor($number * $factor), $factor);
}

// Mixinにまとめる
@mixin check-contrast($foreground, $background) {
  $contrast-ratio: contrast-ratio($foreground, $background);
  $accessibility: success-criterion($contrast-ratio);
  @debug 'コントラスト比:#{$contrast-ratio} #{$accessibility}';
}

使い方

@include で呼び出します。引数に比較するカラーコードを入れます。

// 呼び出し
@include check-contrast(#ffffff, #bf4080); // 出力結果「コントラスト比:4.92 AA」

@debug でコントラスト比と達成基準が出力されます。

ScreenShot 2024-12-04 at 17.55.03.png

DEMO

Sass:Playground に DEMO を置いています。

告知

2024年12月11日に発売予定の Web制作者のためのSassの教科書 改訂3版 に掲載しています。

1
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
1
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?