How do CSS media queries work?
Media queries apply CSS rules only when certain conditions are met - most commonly the viewport width - enabling responsive designs.
CSSLayout
Overview
Media queries let you apply different CSS based on device characteristics like screen width, height, or user preferences (e.g. dark mode). They are the foundation of responsive design. The most common pattern: define mobile styles first, then override with media queries for larger screens (mobile-first).
Key Points
- •Syntax: `@media (condition) { /* CSS */ }`.
- •`min-width` targets screens **at least** that wide (mobile-first approach).
- •`max-width` targets screens **no wider** than that (desktop-first approach).
- •Combine conditions: `@media (min-width: 768px) and (max-width: 1024px)`.
- •User-preference queries: `prefers-color-scheme: dark`, `prefers-reduced-motion: reduce`.
- •Common breakpoints: 640px (sm), 768px (md), 1024px (lg), 1280px (xl).
Examples
Mobile-first responsive layout
css/* Mobile: single column (default, no query) */
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
/* Tablet and up */
@media (min-width: 768px) {
.grid { grid-template-columns: 1fr 1fr; }
}
/* Desktop and up */
@media (min-width: 1024px) {
.grid { grid-template-columns: repeat(3, 1fr); }
}Mobile-first: write the mobile styles first, then add queries for larger screens.
Dark mode via prefers-color-scheme
cssbody {
background: #ffffff;
color: #0f172a;
}
@media (prefers-color-scheme: dark) {
body {
background: #0f172a;
color: #f8fafc;
}
}Reduce motion for accessibility
css.spinner { animation: spin 1s linear infinite; }
@media (prefers-reduced-motion: reduce) {
.spinner { animation: none; }
}Respects users who experience motion sickness from animations.
Hide element on mobile, show on desktop
css.sidebar {
display: none; /* hidden on mobile */
}
@media (min-width: 1024px) {
.sidebar { display: block; }
}Pro Tip
Prefer `min-width` (mobile-first) over `max-width` (desktop-first). Mobile-first means less CSS to override and typically produces cleaner stylesheets. Tailwind CSS uses the same mobile-first convention with its `sm:`, `md:`, `lg:` prefixes.