Some users can prefer to use dark mode or reduce motion on their computer. So, how we can respect their preferences on our website?
For example if you use dark mode on your computer, you'll realize that my website will be dark too. Or if you use reduce motion on your computer, you'll realize that my website will reduce the animations on home page.
In order to do that, we can use css media queries.
Example for dark mode:
.day {
background: #eee;
color: black;
}
.night {
background: #333;
color: white;
}
@media (prefers-color-scheme: dark) {
.day.dark-scheme {
background: #333;
color: white;
}
.night.dark-scheme {
background: black;
color: #ddd;
}
}
@media (prefers-color-scheme: light) {
.day.light-scheme {
background: white;
color: #555;
}
.night.light-scheme {
background: #eee;
color: black;
}
}
.day,
.night {
display: inline-block;
padding: 1em;
width: 7em;
height: 2em;
vertical-align: middle;
}
Example for reduce motion:
/*
If the user has expressed their preference for
reduced motion, then don't use animations on buttons.
*/
@media (prefers-reduced-motion: reduce) {
button {
animation: none;
}
}
/*
If the browser understands the media query and the user
explicitly hasn't set a preference, then use animations
on buttons.
*/
@media (prefers-reduced-motion: no-preference) {
button {
/* `vibrate` keyframes are defined elsewhere */
animation: vibrate 0.3s linear infinite both;
}
}