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: Tr

Dynamic text color contrast based on background lightness with CSS/SVG filters • miunau

submited by
Style Pass
2024-02-12 00:00:04

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:

Traditionally this has been done either with JavaScript or with a preprocessor like SCSS, and more recently by breaking the color components down into HSL as CSS variables and (ab)using calc() to calculate the contrast.

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.

Leave a Comment