Media Queries
@media, breakpoints, mobile-first
Skills taught: css.media-queries, css.breakpoints, css.mobile-first
Basic media query syntax
/* Classic syntax */
@media (min-width: 768px) {
.sidebar { display: block; } /* only on screens >= 768px */
}
/* Modern range syntax (Level 4) */
@media (width >= 768px) {
.sidebar { display: block; }
}
/* Range: between two widths */
@media (600px <= width < 1024px) {
.layout { grid-template-columns: 1fr 1fr; }
}
/* Combining conditions */
@media (min-width: 768px) and (orientation: landscape) {
.hero { min-height: 60vh; }
}
Mobile-first approach (recommended)
/* BASE STYLES — mobile (no query) */
.cards {
display: grid;
grid-template-columns: 1fr; /* single column on mobile */
gap: 16px;
}
nav ul {
display: none; /* hide nav links on mobile */
}
/* TABLET — 640px+ */
@media (min-width: 640px) {
.cards {
grid-template-columns: 1fr 1fr; /* two columns */
}
}
/* DESKTOP — 1024px+ */
@media (min-width: 1024px) {
.cards {
grid-template-columns: repeat(3, 1fr); /* three columns */
}
nav ul {
display: flex;
gap: 24px;
}
}
Tip: Mobile-first is recommended: write base styles for the smallest screen, then add min-width queries for larger screens. Browsers download all CSS but skip applying queries that don't match — mobile devices execute less CSS.
Accessibility media queries
/* Respect OS dark mode preference */
@media (prefers-color-scheme: dark) {
:root {
--bg: #0e1116;
--text: #e2e8f0;
}
}
/* Reduce motion for users who need it */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
/* Coarse pointer (touch device) — make touch targets larger */
@media (pointer: coarse) {
button { min-height: 44px; min-width: 44px; }
}
Frequently Asked Questions
What breakpoints should I use?
Common breakpoints: 640px (small tablets), 768px (tablets), 1024px (laptops), 1280px (desktops). Tailwind CSS uses these exact values. However, design for content — add a breakpoint wherever your layout breaks, not at arbitrary device widths.
Do media queries affect performance?
Browsers download all CSS regardless of media queries. Non-matching queries are not applied but are still parsed. For performance, keep CSS concise rather than worrying about individual media queries.