Introduction
Media queries let you apply CSS rules depending on device width, height, orientation, resolution, color mode, and more. They’re the foundation of responsive design.
1. Basic Media Query
@media (max-width: 600px) {
body {
background: #222;
}
}
2. Common Breakpoints
- Mobile — 480px
- Tablet — 768px
- Laptop — 1024px
- Desktop — 1200px+
3. Example: Responsive Text
h1 { font-size: 32px; }
@media (max-width: 768px) {
h1 { font-size: 24px; }
}
4. Min + Max Width
@media (min-width: 600px) and (max-width: 900px) {
.card {
width: 80%;
}
}
5. Orientation Detection
@media (orientation: portrait) {
.sidebar { display: none; }
}
@media (orientation: landscape) {
.sidebar { display: block; }
}
6. High DPI / Retina Screens
@media (min-resolution: 2dppx) {
img {
filter: contrast(120%);
}
}
7. Dark Mode Detection
@media (prefers-color-scheme: dark) {
body { background: #121212; color: #eee; }
}
8. Reduced Motion Preference
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; }
}
9. Responsive Grid Example
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
@media (max-width: 600px) {
.grid {
grid-template-columns: 1fr;
}
}
10. Responsive Flexbox Layout
.container {
display: flex;
}
@media (max-width: 700px) {
.container {
flex-direction: column;
}
}
11. Breakpoint Naming
@media (--mobile) { ... }
@media (--tablet) { ... }
This is used in modern CSS with custom media.
12. Using Custom Media (CSS4)
@custom-media --small (max-width: 600px);
@media (--small) {
.box { padding: 10px; }
}
13. Print Styles
@media print {
nav, footer { display: none; }
body { background: #fff; color: #000; }
}
14. Accessibility With Media Queries
- Reduce animations
- Improve readability on narrow screens
- Increase tap targets
15. Summary
- Media queries adapt your site to any screen size
- Use min/max-width for responsive breakpoints
- Use orientation, reduced-motion, dark mode for UX improvements
- Combine grid & flexbox with media queries