Bootstrap: Reuse of the color-yiq function

Created on 17 Jul 2017  路  3Comments  路  Source: twbs/bootstrap

With a simple change it is possible to use the color-yiq function with other properties, not just "color"

// Color contrast
@mixin color-yiq($color, $prop: 'color') {
  $r: red($color);
  $g: green($color);
  $b: blue($color);

  $yiq: (($r * 299) + ($g * 587) + ($b * 114)) / 1000;

  @if ($yiq >= 150) {
    #{$prop}: #111;
  } @else {
    #{$prop}: #fff;
  }
}
.element-inside-primary {
  @include color-yiq(theme-color("primary"), 'background-color');
}

Just add the parameter "$prop: 'color'" that we can use other properties
This can be interesting when you want to assign a background that contrasts with a color.

css v4

Most helpful comment

It would be much better to change it to a function, so we can use it for whatever we like. Then the colors #111 and #fff should naturally use some variables so you can customize it.
Additionally it would be nice to provide one or more mixins that utilize the function.

Function

// Color contrast
@function color-yiq($color) {
  $r: red($color);
  $g: green($color);
  $b: blue($color);

  $yiq: (($r * 299) + ($g * 587) + ($b * 114)) / 1000;

  @if ($yiq >= 150) {
    @return $text-black;
  } @else {
    @return $text-white;
  }
}

Mixins

@mixin text-color($color: $body-bg) {
  color: color-yiq($color);
}

or

@mixin color-yiq($color: $body-bg, $prop: 'color') {
  #{$prop}: color-yiq($color);
}

All 3 comments

It would be much better to change it to a function, so we can use it for whatever we like. Then the colors #111 and #fff should naturally use some variables so you can customize it.
Additionally it would be nice to provide one or more mixins that utilize the function.

Function

// Color contrast
@function color-yiq($color) {
  $r: red($color);
  $g: green($color);
  $b: blue($color);

  $yiq: (($r * 299) + ($g * 587) + ($b * 114)) / 1000;

  @if ($yiq >= 150) {
    @return $text-black;
  } @else {
    @return $text-white;
  }
}

Mixins

@mixin text-color($color: $body-bg) {
  color: color-yiq($color);
}

or

@mixin color-yiq($color: $body-bg, $prop: 'color') {
  #{$prop}: color-yiq($color);
}

A PR is welcome.

Mixin was renamed to be a function in #24426.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eddywashere picture eddywashere  路  3Comments

knownasilya picture knownasilya  路  3Comments

devdelimited picture devdelimited  路  3Comments

matsava picture matsava  路  3Comments

fohlsom picture fohlsom  路  3Comments