Hey fellow creators,
Let's learn how to switch images when using a dark/light mode.
If you prefer to watch the video version, it's right here :
1. How to handle the dark mode.
You only need to add a media query so that, when you change the mode from light to dark in your computer settings, the theme of your app changes from light to dark. Here's how to do it:
@media (prefers-color-scheme: dark){
body {
background: #000;
}
}
Now, there are two ways to change images when you switch from dark to light mode (or the other way around). Let's take a look at the first one!
2. The first way to switch images.
You can wrap the images inside a picture element.
<picture>
<source srcset="ressources/dark-empire.jpg" media="(prefers-color-scheme:dark)">
<img src="ressources/light-empire.jpg">
</picture>
That way, if you've selected dark theme in your settings, then it will choose the first image, if not it will choose the second one.
Then, you can style the images however you want! Here's how I did it:
img {
width: 500px;
height: 600px;
object-fit: cover;
object-position: center;
display: block;
margin: 0 auto;
position: relative;
top: 70px;
}
3. The second way to switch images.
But there's another way to do this! You can create an empty div in HTML and then add the image as a background of this div.
<div class="img-toggle">
</div>
.img-toggle {
width: 500px;
height: 600px;
display: block;
margin: 0 auto;
position: relative;
top: 70px;
background: url(ressources/light-empire.jgp) center / cover;
}
However, you then need to update your media query so that you have the darker image for the dark mode and not the lighter image.
@media (prefers-color-scheme: dark){
body {
background: #000;
}
.img-toggle {
background: url:url(ressources/dark-empire.jgp) center / cover;
}
}
You've done it! Now your dark theme can be even darker than before ;)
Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool
Enzo.
Top comments (2)
One other option is to use prefers-color-scheme within an inline SVG. Good for icons.
You could also use inline SVG to wrap images and add theme effects on the SVG.
Can this be applied to an html table email signature that uses images that are linked/sourced on the web?