Media queries let you apply CSS based on device or user characteristics (viewport width, orientation, color scheme, motion preference, input type, resolution, and more). The recommended strategy is mobile-first: write base styles for small screens, then enhance with min-width breakpoints.
CSS Media Queries
1) Mobile-First Breakpoints (min-width)
/* Base styles (phones) */
.cards { grid-template-columns: repeat(2, 1fr); }
/* ≥ 576px */
@media (min-width: 576px) {
.cards { grid-template-columns: repeat(3, 1fr); }
}
/* ≥ 768px, ≥ 992px … likewise */
Card 1
Card 2
Card 3
Card 4
Card 5
Card 6
Card 7
Card 8
2) max-width & Ranges
/* Only up to tablets */
@media (max-width: 767px) {
.panel { background: #FFFDE7; }
}
/* Between 768px and 1024px (level 4 syntax) */
@media (768px <= width <= 1024px) {
.panel { border-color: #90CAF9; }
}
Try shrinking/expanding the viewport to see background/border changes.
3) Orientation
@media (orientation: landscape) { .orient { background: #FFF3E0; } }
@media (orientation: portrait) { .orient { background: #E3F2FD; } }
Rotate device to see style change
4) Dark Mode: prefers-color-scheme
@media (prefers-color-scheme: dark) {
:root { --bg: #0d1117; --fg: #c9d1d9; }
}
System Dark Mode Demo
This panel follows your OS/browser dark mode setting.
5) Reduced Motion: prefers-reduced-motion
@media (prefers-reduced-motion: reduce) {
.bounce { animation: none; }
}
Animated Button
If your system prefers reduced motion, the animation stops.
6) Input Capability: hover & pointer
@media (hover: hover) and (pointer: fine) {
.button-like:hover { background: #C8E6C9; }
}
@media (hover: none) and (pointer: coarse) {
.button-like { padding: 14px 18px; }
}
7) Resolution Queries
@media (min-resolution: 2dppx) {
.hires { box-shadow: 0 0 0 2px rgba(144,202,249,.15) inset; }
}
On high-DPI/retina screens, this panel gets a subtle inset highlight.
Best Practices:
- Prefer
min-width(mobile-first). Add enhancements as screens get larger. - Use logical ranges (e.g.,
(768px <= width < 1024px)) for clarity where supported. - Don’t rely only on width—respect user preferences like dark mode and reduced motion.
- Consider input capability with
hover/pointerto improve touch UX.