Highest contrast colour in pure CSS

I’m setting up a button component with a few different variants (.btn-primary, .btn-success, .btn-danger, that sort of thing)—these switch the background colour. Is there a way to set this up so the foreground colour is automatically selected between a dark and light option for whichever gives the most contrast? In pure CSS that is, rather than using some JavaScript.

Being able to do an if-then-else for whether the L component of var(—btn-bg) is <50 would do the trick to select between the two as an approximation, but I’m not sure how to go from there. Is this possible?
Was this page helpful?