Have you ever encountered a situation where you added a “black on white” image on a web page, only to find out that when switching to dark mode, the background changes to black while the image remains white on black? It can be frustrating, but fear not, as there is a solution using CSS.
To address this issue, you can utilize CSS to automatically invert the colors of elements and images when dark mode is enabled. By applying a simple rule to your CSS, you can detect dark mode and adjust the image accordingly. Here’s an example of how you can achieve this:
@media (prefers-color-scheme: dark) {
.my-image {
filter: invert(100%);
}
}
In the above code snippet, we use the @media
rule along with the (prefers-color-scheme: dark)
media query to target devices that are in dark mode. Inside the media query, we select the desired image using the .my-image
class and apply the filter
property with the value invert(100%)
. This effectively flips the colors of the image, making it visible and readable in dark mode.
It’s important to note that while this approach works in most cases, it may not be 100% accurate if your dark background color is not perfectly black. However, even with this limitation, it is still a significant improvement over having a white image on a dark background.
To go a step further and ensure a seamless transition between light and dark modes, you can also consider using a CSS background image instead of the traditional <img>
tag in HTML. This way, you can easily swap out the image in dark mode, ensuring optimal visibility and accessibility for users.
By implementing these techniques, you can ensure that your web design adapts to dark mode and provides a better user experience across different devices and preferences.
Tags: CSS, dark mode, invert colors, web development