This content originally appeared on DEV Community and was authored by Ustariz Enzo
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/Learntocreate/videos
Follow me on my social medias:
Instagram : https://www.instagram.com/learn_to_create1
TikTok : https://www.tiktok.com/@learn_to_create
Twitter : https://twitter.com/Learn_To_Create
See you soon for some easy-to-learn tutorials!
Enzo.
This content originally appeared on DEV Community and was authored by Ustariz Enzo
Ustariz Enzo | Sciencx (2021-10-27T07:41:58+00:00) Switch to a darker image when on dark mode!. Retrieved from https://www.scien.cx/2021/10/27/switch-to-a-darker-image-when-on-dark-mode/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.