How to Change an HTML Image URL in Dark Mode
In today’s blog post, we’ll explore a simple HTML technique to change an image URL specifically for dark mode. While CSS makes it easy to apply style changes based on the system’s preference for dark mode using the prefers-color-scheme
media feature, we often come across situations where we need to change the image itself, rather than applying a CSS rule.
One way to achieve this is by utilizing the picture
tag to wrap the img
tag. Here’s an example:
1 | <picture> |
In the code snippet above, we define two image sources. The dark.png
image will be used if dark mode is supported and enabled. On the other hand, if the system is in light mode, the light.png
image will be used as a fallback.
This technique is well-supported across various browsers. Older browsers that do not implement the picture
tag or do not support dark mode will gracefully fall back to displaying the light.png
image.
One important thing to note is that the browser doesn’t download both images. Instead, it only downloads the image appropriate for the current mode. This ensures efficient bandwidth usage and eliminates any wastage.
If you’re interested in learning more about dark mode, feel free to check out my blog post on dark mode.
That’s it! Now you know how to change the HTML image URL specifically for dark mode. Happy coding!
tags: [“HTML”, “CSS”, “dark mode”, “image”, “media feature”]