iTranslated by AI
[HTML/CSS] How to Switch Images for Dark Mode
There may be times when you want to use optimized images for dark mode instead of regular ones. Especially for icons, you might want to switch from black-based ones to white-based ones to match the text color. Here is how to switch them. You can switch images using native HTML and CSS features without using JavaScript.
Here is a sample
In the case of the <img> tag
When loading images with the <img> tag, you can achieve this by combining the <picture> tag and <source> tags.
<picture>
<!-- For dark mode -->
<source
srcset="hoge-dark.jpg"
media="(prefers-color-scheme: dark)"
/>
<!-- For light mode -->
<source srcset="hoge.jpg" />
<img
src="hoge.jpg"
alt="hoge"
width="300"
height="300"
/>
</picture>
The <source> tag allows you to specify conditions similar to media queries using the media attribute. Here, the image for dark mode is specified with (prefers-color-scheme: dark). The <picture> tag evaluates <source> tags from top to bottom to see if there is one that matches the conditions. For users who have specified dark mode, the first one matches, and for light mode or if unspecified, the second regular image matches. This completes the image switching for the <img> tag.
In the case of CSS background-image
For CSS background images, you can switch them using the media query mentioned earlier.
/* For light mode */
.bg {
background-image: url("hoge.jpg");
}
/* For dark mode */
@media (prefers-color-scheme: dark) {
.bg {
background-image: url("hoge-dark.jpg");
}
}
For users in dark mode, the property is overwritten by the property inside the @media (prefers-color-scheme: dark) media query, so the image for dark mode is specified for the background-image property. This completes the switching for CSS background images.
Bonus: How to check in the browser
As an aside, here is how to emulate prefers-color-scheme in Chrome and Firefox.
In the case of Chrome
Open the Developer Tools, and you can switch it using the icon at the top of the pane where you can check the CSS in the Elements tab.

In the case of Firefox
In Firefox, open the Developer Tools. In the Rules view of the Inspector tab, where you can see the applied CSS, there are sun and moon icons. Clicking these allows you to emulate each color scheme.

Discussion