One of my CSS pet peeves has been components where I want to dynamically have either a white or black text color based on the background lightness:
This will invert the text color, grayscale it, increase its brightness, and increase its contrast. The mix-blend-mode is there to make sure the text color doesn't affect the background color. The opacity is there to make sure the text color doesn't become too bright.
This will turn to black around #AAAAAA. You can adjust brightness lower if you want it to turn to black earlier. mia made a codepen to play around with this.
Drawbacks: There is noticeable fringing right at the edge of the color switch. This happens as the contrast gets slammed to the maximum, and the antialiased colors around the edges of the font get to pick from a semi-random binary choice of black or white depending on the geometry. The browser doesn't do a great job of antialiasing that either.