CSS How to Use Media Query for Dark Mode
@media (prefers-color-scheme: dark) to apply styles when the user prefers dark mode, for example: @media (prefers-color-scheme: dark) { body { background: black; color: white; } }.Examples
How to Think About It
prefers-color-scheme media feature. Write CSS inside @media (prefers-color-scheme: dark) to style elements for dark mode. This way, the browser automatically applies these styles if the user prefers dark colors.Algorithm
Code
@media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: #e0e0e0;
}
}
body {
background-color: white;
color: black;
}Dry Run
Let's trace how the browser applies styles when user prefers dark mode.
Check user preference
User's system preference is dark mode.
Apply media query styles
Browser applies styles inside @media (prefers-color-scheme: dark) block.
Render page
Background is #121212 and text color is #e0e0e0.
| Step | User Preference | Applied Background | Applied Text Color |
|---|---|---|---|
| 1 | dark | none yet | none yet |
| 2 | dark | #121212 | #e0e0e0 |
| 3 | dark | #121212 | #e0e0e0 |
Why This Works
Step 1: Detect user preference
The media query prefers-color-scheme checks if the user prefers dark or light mode.
Step 2: Apply conditional styles
CSS inside @media (prefers-color-scheme: dark) runs only if dark mode is preferred.
Step 3: Automatic switching
The browser automatically switches styles based on system settings without extra JavaScript.
Alternative Approaches
if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { document.body.style.backgroundColor = '#121212'; document.body.style.color = '#e0e0e0'; }
body.dark-mode { background-color: #121212; color: #e0e0e0; }Complexity: O(1) time, O(1) space
Time Complexity
Applying media queries is handled by the browser instantly without loops, so it is constant time.
Space Complexity
No extra memory is needed beyond CSS rules, so space complexity is constant.
Which Approach is Fastest?
Using pure CSS media queries is fastest and most efficient compared to JavaScript detection.
| Approach | Time | Space | Best For |
|---|---|---|---|
| CSS media query | O(1) | O(1) | Automatic, efficient dark mode styling |
| JavaScript detection | O(1) | O(1) | Dynamic control but more complex |
| Manual toggle | O(1) | O(1) | User-controlled theme switching |