How to change HTML image URL in dark mode

If the system is in dark mode, the changes can be easily applied using CSS, usingprefers-color-schemeMedia function.

View my blog post onDark modeIf you want to learn more about it.

Today, I ran into a problem-how to change the image defined in HTML instead of CSS rules?

It turns out that there is a simple HTML way to do this without involving any CSS or JavaScript.

We can usepictureLabel to packageimglabel:

    media="(prefers-color-scheme: dark)">
  <img src="light.png">

If dark mode is supported and enabled, thendark.pngThe picture will be used asimglabel.

The mark is well supported, and older browsers that do not implement the mark or dark mode will fall back to the position where the mark is displayed.light.pngimage.

It is important to note that the browser will not download 2 pictures under any circumstances: if it is in dark mode, in this example, it will only download 2 pictures.dark.pngPicture, if it is in light color mode, it will only downloadlight.png, So bandwidth is not wasted.

Download mine for freeHTML manual

More HTML tutorials: