media

@media

Applies contained CSS rules only when the specified media query matches the user's device, viewport, or environment. It is the foundation of responsive design and print-specific styling.

@media <media-query-list> { <rules> }

Common conditions / descriptors

Descriptor Purpose
(min-width: 768px) Match viewports at least 768px wide (mobile-first breakpoint)
(max-width: 767px) Match viewports up to 767px wide (desktop-first breakpoint)
(prefers-color-scheme: dark) Match users who prefer a dark UI theme
(prefers-reduced-motion: reduce) Match users who requested reduced motion
(orientation: landscape) Match landscape viewport orientation
print Apply only when the document is being printed
(hover: hover) Match devices whose primary input can hover
(aspect-ratio: 16/9) Match a specific viewport aspect ratio

Examples

@media (min-width: 768px) {
  .grid { grid-template-columns: repeat(3, 1fr); }
}

Switch to a 3-column grid on tablet and up

@media (prefers-color-scheme: dark) {
  :root { --bg: #0b0b0f; --fg: #f5f5f7; }
}

Apply dark theme tokens when the OS is set to dark

@media print {
  nav, .ads { display: none; }
  body { color: #000; }
}

Hide navigation and ads, force black text when printing

@media (min-width: 640px) and (max-width: 1023px) {
  .sidebar { width: 240px; }
}

Target a bounded tablet range using 'and'

Gotcha

Use mobile-first min-width queries so smaller screens get the default styles. Range syntax `@media (width >= 768px)` is now widely supported but check target browsers before dropping the legacy form.

Related at-rules

← All CSS at-rules · CSS properties · CSS selectors