Calculate Accessible Colors Against Background Color in SCSS

CMy website is not perfect when it comes to accessibility, and I am by no means an accessibility expert. But I strive to be better and have improved the color contrast ratio of my text in the past. However, some parts of my site were still not as accessible as I liked them to be. The color scheme for code markup was especially bad to read, however. For some text, the contrast of the text-color to the background-color was as low as 1.08:1. To meet the minimum requirement
(Level AA) for color contrast
of the “Web Content Accessibility Guidelines (WCAG) 2.1”, the contrast needs to be 4.5:1 for normal text.

The visual presentation of text and images of text has a contrast ratio of at least 4.5:1

My code color scheme missed this minimum by a mile in most situations:

Screenshot of a code snippet from this side with barely legible text

I went searching for a solution that can calculate the luminance dynamically in Sass—for both a dark and a light color scheme—without me having to change my base colors. I came across the article “Programming Sass to Create Accessible Color Combinations” by Jason Hogue published on CSS-Tricks. The information given in the article and the solution are pure gold.

If you’re only interested in the code, it’s on GitHub. It needs some minor changes to get rid of deprecation-warnings in Dart-Sass 1.33.0.

Without changing my original colors, these are the results for a light and dark theme, that now fulfil the Level AA minimum requirements for the contrast criterion of WCAG 2.1:

Screenshot of the same code snippet, this time with better text/background contrast in light mode
Screenshot of the same code snippet, this time with better text/background contrast in dark mode