Skip to content

05 Color contrast calculation

tei187 edited this page Apr 23, 2024 · 2 revisions

Color contrast refers to the difference between two colors in terms of their visibility and perception by the human eye. It is an important design element in visual communication and helps to ensure that important information is easily distinguishable from the background.

There are two types of color contrast: achromatic and chromatic. Achromatic color contrast refers to the difference in brightness between two colors, while chromatic color contrast refers to the difference in hue (i.e., the color of a color).

In general, achromatic color contrast is easier to achieve and is often sufficient for ensuring legibility. However, in some cases, it may be necessary to also consider chromatic color contrast to ensure that the differences between different colors are also easily distinguishable.

Overall, color contrast is an important consideration in design to ensure that information is clearly communicated and easy to read or understand.




Color contrast calculation is based on each models' method called getContrast(). It is required to pass only one argument, being an object of specific color model. The second argument is rounding precision (integer value or null). The third is a boolean flag, if the outcome should be returned as a ratio to 1.

use tei187\ColorTools\ColorModels\HSL;

$swatch1 = new HSL;
$swatch1->setValues(46, 1, .5);

$swatch2 = new HSL;
$swatch2->setValues(46, .3, .2);

# direct calculation
  $swatch1->getContrast($swatch2);
  // float(7.4096678210433)

# calculation with rounding
  $swatch1->getContrast($swatch2, 2);
  // float(7.41)

# calculation with rounding and formatting to string with a:b syntax
  $swatch1->getContrast($swatch2, 2, true);
  // string(6) "7.41:1"