Color scheme

2 snippets in HTML & CSS

HCHTML & CSS

Media Query Features

HC · Responsive Design
Syntax
@media (prefers-color-scheme: dark) { }
@media (prefers-reduced-motion: reduce) { }
@media (hover: hover) { }
@media (orientation: portrait) { }
Example
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0f172a;
    --text: #e2e8f0;
  }
}

@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

@media (hover: hover) {
  .card:hover { transform: translateY(-2px); }
}

Note prefers-color-scheme detects dark/light mode system preference. prefers-reduced-motion is critical for accessibility. hover: hover avoids applying hover styles on touch devices where hover is awkward.

Light-Dark Function

HC · Modern CSS
Syntax
color-scheme: light dark;
color: light-dark(light-value, dark-value);
Example
:root {
  color-scheme: light dark;
}

body {
  background: light-dark(#ffffff, #0f172a);
  color: light-dark(#1e293b, #e2e8f0);
}

.card {
  background: light-dark(#f8fafc, #1e293b);
  border: 1px solid light-dark(#e2e8f0, #334155);
}

Note light-dark() provides dark mode support inline without media queries. It uses the color-scheme property to determine which value to use. Declare color-scheme: light dark on :root to enable it. This is much simpler than managing separate media query blocks for colors.

Frequently asked questions

How does HTML & CSS handle color scheme?
HTML & CSS covers this with 2 copy-ready snippets on this page. The "Media Query Features" snippet in HTML & CSS uses `@media (prefers-color-scheme: dark) { }`.
Which code does the HTML & CSS example use?
The "Media Query Features" snippet uses `@media (prefers-color-scheme: dark) { }`, from the Responsive Design section of the HTML & CSS cheat sheet.
What other HTML & CSS snippets are shown for "color scheme"?
Besides "Media Query Features", this page also shows "Light-Dark Function".
Is there anything to watch out for?
Yes. For "Media Query Features": prefers-color-scheme detects dark/light mode system preference. prefers-reduced-motion is critical for accessibility. hover: hover avoids applying hover styles on touch devices where hover is awkward.