Let the browser pick a legible black or white foreground for a dynamic background with the CSS contrast-color() function, instead of hard-coding colour pairs or computing luminance in JavaScript.
CSS Color Module Level 5 — contrast-color()
WCAG 1.4.3 — Contrast (Minimum) (Level AA)
How to have the browser pick a contrasting color in CSS