Skip to content
colors

getContrastColor

The `getContrastColor` function automatically chooses black (`#000000`) or white (`#ffffff`) based on which provides the best contrast against a given background color. It is useful for ensuring text remains legible regardless of background.

1 min read133 words

Function Signature

js

getContrastColor(bgHex: string): "#000000" | "#ffffff"

Parameters

  • bgHex (string): The background color as a HEX string (e.g., #ff6600).

Return Value

Returns either #000000 or #ffffff, whichever yields the higher WCAG contrast ratio against the input background.

js

getContrastColor("#ff6600");
// "#000000"

getContrastColor("#333333");
// "#ffffff"

getContrastColor("#00aaff");
// "#000000"

Examples

js

// Bright background → dark text
console.log(getContrastColor("#ffff00"));
// "#000000"

// Dark background → light text
console.log(getContrastColor("#111111"));
// "#ffffff"

Implementation Details

  • Uses the contrastRatio function to compare input background against white and black.
  • Computes both ratios, returns the color with the higher ratio.
  • Guarantees compliance with WCAG contrast standards for either choice.

Usage Notes

  • Primarily used for determining accessible text colors against dynamic backgrounds.
  • Does not attempt to generate custom colors—strictly black or white.
  • Light backgrounds will yield black text, dark backgrounds yield white text.

Previous

ensureContrast

Next

deltaE76


Top tools

BoardlyLinksyChromoCodeHub

ReadyTools

CareersContactTools
Pricing7 days free
GuidesDocsBlogUpdatesLaraVault

Select Language

Set theme

© 2026 ReadyTools. All rights reserved.