DEV Community

Yuiko Koyanagi
Yuiko Koyanagi

Posted on

How to Automatically Adjust Colors in High Contrast Mode

Introduction

I recently received a bug report where an SVG icon was not displaying correctly in high contrast mode. In this article, I’ll share the solution that worked for me.

Solution

In high contrast mode, I used the CanvasText system color to automatically adjust the icon's color.

.icon {
  mask-image: url(svg-link);
  background-color: currentColor;
  ...
}

@media (forced-colors: active) {
  .icon::before {
    background-color: CanvasText;
  }
}
Enter fullscreen mode Exit fullscreen mode

In my case, I initially used currentColor to inherit the color from the parent element. However, in high contrast mode, I wanted to set the background-color to CanvasText universally within the child element, so I applied this change.

What is CanvasText?

CanvasText refers to the text color used for application content or documents. It automatically adjusts to provide the best contrast against the system's background color.

By using CanvasText, you ensure that text and icons remain visible even when the user enables high contrast mode. Additionally, since CanvasText adapts based on the system's theme, it works well with both dark and light modes.

In my case, the icon's background-color was initially set to black. However, when the background turned black in high contrast mode, the icon became invisible. Changing the color to white made it visible again, but to handle this consistently across all scenarios, I opted to use the system color CanvasText.

References

https://developer.mozilla.org/en-US/docs/Web/CSS/system-color

Top comments (0)