What is prefers-color-scheme in CSS: Dark Mode Detection
prefers-color-scheme is a CSS media feature that detects if a user prefers a light or dark color theme on their device. It helps websites automatically adjust their colors to match the user's system theme, improving comfort and readability.How It Works
The prefers-color-scheme media feature checks the user's device or browser settings to see if they prefer a light or dark color theme. Think of it like asking your friend if they want the room lights bright or dim before entering, so you can adjust the lighting to their comfort.
When a website uses this feature, it can apply different CSS styles depending on the user's preference. For example, if the user prefers dark mode, the site can switch to darker backgrounds and lighter text automatically. This makes the browsing experience easier on the eyes, especially in low light.
It works by using media queries in CSS, similar to how websites adjust layout for different screen sizes. The browser tells the website the preferred color scheme, and the site responds with matching styles.
Example
This example shows how to use prefers-color-scheme to switch background and text colors based on user preference.
body {
background-color: white;
color: black;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: #e0e0e0;
}
}When to Use
Use prefers-color-scheme when you want your website or app to respect the user's system theme preference automatically. This is especially useful for improving accessibility and user comfort.
Common use cases include enabling dark mode for night-time browsing, reducing eye strain, and matching the overall look and feel of the user's device. It also helps create a modern, polished experience without requiring users to toggle themes manually.
Key Points
- prefers-color-scheme detects light or dark mode preference.
- It uses CSS media queries to apply different styles.
- Improves user experience by matching system themes.
- Supported by most modern browsers.
- Works without JavaScript, purely in CSS.
Key Takeaways
prefers-color-scheme lets websites detect if users prefer light or dark mode.prefers-color-scheme without extra setup.