DEV Community

Yuiko Koyanagi
Yuiko Koyanagi

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay