The prefers-color-scheme
media feature is used to detect if the user has requested a light or dark color theme in their operating system or browser settings. This is essential for creating user-friendly dark modes.
Example 1: Dark Mode Styles
/* styles.css */
/* Styles for users who prefer a dark color scheme */
@media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: #ffffff;
}
}
Explanation
This code checks if the user's system is set to a dark theme. If so, it changes the body
background to a dark color and the text color to light, creating a basic dark mode.
Example 2: Light Mode Styles
/* styles.css */
/* Explicitly define light mode styles for users who prefer it */
@media (prefers-color-scheme: light) {
body {
background-color: #ffffff;
color: #333333;
}
}
Explanation
While often the default, explicitly defining light theme styles can be useful. This ensures a consistent light theme for users who have specifically chosen it in their system preferences.
Example 3: Overriding Dark Mode for a Specific Element
/* styles.css */
/* Force a light theme for a specific component, even in dark mode */
@media (prefers-color-scheme: dark) {
.light-widget {
background-color: #f8f9fa;
color: #212529;
border: 1px solid #dee2e6;
}
}
Explanation
This example shows how to keep a specific element, .light-widget
, styled with a light theme even when the rest of the page is in dark mode. This can be useful for embedded content or ads.
Example 4: Adjusting Images for Dark Mode
/* styles.css */
/* Dim images slightly in dark mode to reduce brightness */
@media (prefers-color-scheme: dark) {
img {
filter: brightness(0.8) contrast(1.2);
}
}
Explanation
Bright images can be jarring in a dark theme. This CSS applies a filter to all img
elements in dark mode, slightly reducing their brightness and increasing contrast for better visual comfort.
Example 5: Using CSS Custom Properties for Theming
/* styles.css */
/* Define color variables for light and dark themes */
:root {
--bg-color: #fff;
--text-color: #000;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #222;
--text-color: #eee;
}
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
Explanation
This is a modern and efficient way to handle theming. It defines CSS Custom Properties (variables) for colors and then redefines them within the prefers-color-scheme: dark
media query, making theme management clean and scalable.