"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Automatically Adjust Colors in High Contrast Mode

How to Automatically Adjust Colors in High Contrast Mode

Published on 2024-08-29
Browse:235

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;
  }
}

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

Release Statement This article is reproduced at: https://dev.to/toffy/how-to-automatically-adjust-colors-in-high-contrast-mode-p4h?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3