getContrastingTextColor
A util for determining an accessible, predefined contrasting text color based on a provided color value.
If the provided color is
- dark, the returned text color will be
#FFFFFF(white); - light, the returned text color will be
#27282A(ice-900).
Import
import { getContrastingTextColor } from '@leaflink/stash-vue/utils/getContrastingTextColor';Typing (Stash color names)
When passing a Stash color name, prefer the types from @leaflink/stash-types:
import type { StashColorNames, StashColorNamesWithShades } from '@leaflink/stash-types/colors';Usage
Providing a hex value
getContrastingTextColor('#C801CC');
getContrastingTextColor('f0f');Providing a Stash color
getContrastingTextColor('seafoam-700');
getContrastingTextColor('purple-100');
getContrastingTextColor('purple'); // equal to `purple-500`TIP
When providing a primary color group name without a shade included, it will always map to its 500 shade variant.
Notes
When you pass a Stash color name (e.g. seafoam-700 or purple), this util resolves it at runtime using CSS variables (so it requires Stash theme tokens to be present in the document).
In SSR (or when document is unavailable), Stash color names fall back to the default contrast color #27282A. Hex inputs do not require CSS variables and can be used in SSR.
Fallback
If an invalid color value is provided, it will return dark text #27282A (ice-900).
Playground
(Hex Value will take priority)
Note: Playground fields are listed in priority order.
INFO
Based on https://wunnle.com/dynamic-text-color-based-on-background, which adheres to WCAG guidelines.