Preference Queries
Overview
Modern CSS doesn't just respond to screen size; it responds to the user's physical and digital environment. Operating systems now allow users to set global preferences for things like Dark Mode, High Contrast, or Reduced Motion (for users prone to motion sickness/seizures). CSS Preference Queries allow your website to seamlessly hook into these OS-level signals and rewrite your styles to accommodate the user's needs automatically.
Syntax
/* 1. Dark Mode */
@media (prefers-color-scheme: dark) {
body {
background-color: #121212;
color: #ffffff;
}
}
/* 2. Reduced Motion (CRITICAL for accessibility) */
@media (prefers-reduced-motion: reduce) {
* {
/* If the user is prone to motion sickness,
violently kill ALL CSS animations instantly! */
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* 3. High Contrast (For visually impaired users) */
@media (prefers-contrast: high) {
.subtle-gray-text {
color: #000000; /* Force it to solid black */
font-weight: 900;
}
}Common Pitfalls
- Ignoring
prefers-reduced-motion. Complex parallax scrolling or aggressive loading animations can physically induce nausea or vestibular seizures in disabled users. It is an absolute professional requirement to disable heavy motion if this OS flag is detected. - Hardcoding Dark Mode via classes (
.dark-mode) WITHOUT checking the OS preference first. The best UX automatically reads the user'sprefers-color-schemeon first load, applies it, and THEN allows them to manually toggle it if they choose.
Interview Questions
Chrome/Edge DevTools has a 'Rendering' tab (Command+Shift+P -> 'Show Rendering'). You can forcefully emulate 'prefers-color-scheme: dark' or 'prefers-reduced-motion: reduce' directly in the browser to test your CSS.
Real-World Example
Using CSS Custom Properties to handle Dark Mode cleanly via a Preference Query.
:root {
--surface: #ffffff;
--text: #333333;
}
/* Automatically invert the variables if the OS is in Dark Mode! */
@media (prefers-color-scheme: dark) {
:root {
--surface: #121212;
--text: #e0e0e0;
}
}
body {
background: var(--surface);
color: var(--text);
}Check Your Knowledge
Test your understanding of Preference Queries with these quick questions.