Function Repository Resource:

FontColorFromBackgroundColor

Source Notebook

Determine an appropriate font color from a given background color

Contributed by: Andrew Steinacher

ResourceFunction["FontColorFromBackgroundColor"][c]

returns an appropriate font color of either Black or White based on W3C recommendations for a given background color c.

Details and Options

This follows W3C Web Content Accessibility Guidelines to maximize contrast.
ResourceFunction["FontColorFromBackgroundColor"] also supports colors given as GrayLevel.

Examples

Basic Examples (2) 

Find an appropriate font color when using blue as a background color:

In[1]:=
fontColor = ResourceFunction["FontColorFromBackgroundColor"][Blue]
Out[1]=

Test the example:

In[2]:=
Panel[Style["This is test.", fontColor], Background -> Blue]
Out[2]=

Test on a wider variety of background colors:

In[3]:=
$testColors = {Red, Blue, White, Orange, Green, Yellow, Brown, Gray, LightGray, Black, White, Purple, Darker@Green};
AssociationMap[ResourceFunction[
  "FontColorFromBackgroundColor"], $testColors] // RightComposition[
  KeyValueMap[Panel[Style["Text", #2], Background -> #1] &],
  Multicolumn
  ]
Out[4]=

Scope (1) 

Find an appropriate font color for a GrayLevel background:

In[5]:=
fontColorForGrayBackground = ResourceFunction["FontColorFromBackgroundColor"][GrayLevel[0.7]]
Out[5]=
In[6]:=
Panel[Style["This is test.", fontColorForGrayBackground], Background -> GrayLevel[0.7]]
Out[6]=

Publisher

Andrew Steinacher

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 10 January 2019

License Information