CSS Media Queries
Apply CSS conditionally based on screen width, device capabilities, and user preferences using @media rules.
Overview
Key Points
- •@media (min-width: 768px) mobile-first: applies when viewport is 768px or wider
- •@media (max-width: 767px) desktop-first: applies when viewport is less than 768px
- •Mobile-first (min-width) is the preferred approach for modern CSS
- •@media (prefers-color-scheme: dark) detects system dark mode
- •@media (prefers-reduced-motion: reduce) respects the user's motion preference
- •Multiple conditions: @media (min-width: 768px) and (max-width: 1023px)
- •Use logical operators: and, not, or (comma = or)
Examples
Mobile-first responsive grid
/* Mobile: single column */
.card-grid {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
/* Tablet: 2 columns */
@media (min-width: 640px) {
.card-grid {
grid-template-columns: repeat(2, 1fr);
}
}
/* Desktop: 3 columns */
@media (min-width: 1024px) {
.card-grid {
grid-template-columns: repeat(3, 1fr);
}
}Writing mobile styles first means no media query is needed for the smallest viewport.
Dark mode with prefers-color-scheme
:root {
--bg: #ffffff;
--text: #0f172a;
--border: #e5e7eb;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f172a;
--text: #f1f5f9;
--border: #1e293b;
}
}
body {
background: var(--bg);
color: var(--text);
}Combining CSS variables with media queries makes theme switching clean and maintainable.
Respecting reduced motion preference
/* Default: with animations */
.animated {
transition: transform 0.3s ease;
animation: pulse 2s infinite;
}
/* Users who prefer no motion */
@media (prefers-reduced-motion: reduce) {
.animated {
transition: none;
animation: none;
}
}Always provide a prefers-reduced-motion fallback for users with vestibular disorders.
Common Mistakes
- Writing max-width styles first (desktop-first) and then fighting specificity for mobile styles
- Using exact pixel breakpoints tied to specific devices design to your content, not to device names
- Forgetting the viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1"> without it, media queries do not work on mobile
Note
You do not need a breakpoint for every device. Add a media query when your content breaks when text becomes too long, images too small, or layout awkward. Let the content, not device specs, determine breakpoints.
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4