Media Queries
Make your website adapt to different screen sizes
Media Queries
Media queries let you apply different styles based on the device's characteristics - most commonly screen width.
Basic Syntax
/* Styles for screens 768px and narrower */
@media (max-width: 768px) {
.sidebar {
display: none;
}
}
/* Styles for screens 769px and wider */
@media (min-width: 769px) {
.container {
max-width: 1200px;
}
}
CSSMobile-First Approach
Start with mobile styles, then add complexity for larger screens:
/* Base styles (mobile) */
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
/* Tablet and up */
@media (min-width: 768px) {
.grid {
grid-template-columns: repeat(2, 1fr);
}
}
/* Desktop and up */
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(3, 1fr);
}
}
CSSCommon Breakpoints
| Name | Width | Typical Devices |
|---|---|---|
| Small | < 640px | Phones (portrait) |
| Medium | 640px–768px | Phones (landscape), small tablets |
| Large | 768px–1024px | Tablets |
| XL | 1024px–1280px | Small laptops |
| 2XL | > 1280px | Desktops |
Combining Conditions
/* Between 768px and 1024px */
@media (min-width: 768px) and (max-width: 1024px) {
/* Tablet-only styles */
}
/* Dark mode preference */
@media (prefers-color-scheme: dark) {
body {
background: #1a1a1a;
color: #e0e0e0;
}
}
/* Reduced motion preference */
@media (prefers-reduced-motion: reduce) {
* {
animation: none !important;
transition: none !important;
}
}
/* Print styles */
@media print {
.no-print, nav, footer {
display: none;
}
}
CSSResponsive Typography
/* Fluid typography using clamp() */
h1 {
font-size: clamp(1.5rem, 4vw, 3rem);
/* Minimum 1.5rem, scales with viewport, maximum 3rem */
}
body {
font-size: clamp(1rem, 1.5vw, 1.25rem);
}
CSSResponsive Images
img {
max-width: 100%;
height: auto;
}
CSS<!-- Serve different images based on screen size -->
<picture>
<source media="(min-width: 1024px)" srcset="hero-large.jpg">
<source media="(min-width: 640px)" srcset="hero-medium.jpg">
<img src="hero-small.jpg" alt="Hero image">
</picture>
HTML