Responsive Design & Media Queries
One site, every screen
More than half of web traffic comes from phones, so pages must adapt to any width.
The essentials
- The viewport meta tag in
<head>:<meta name="viewport" content="width=device-width, initial-scale=1"> - Flexible units:
%,rem,fr, andmax-widthinstead of fixed widths. - Flexible media:
img { max-width: 100%; height: auto; } - Media queries for layout changes.
Mobile-first media queries
Write the phone styles first, then add rules for bigger screens:
.cards { display: grid; gap: 16px; } /* phones: 1 column */
@media (min-width: 640px) { /* tablets */
.cards { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 1024px) { /* desktops */
.cards { grid-template-columns: repeat(4, 1fr); }
}
Common breakpoints: 640, 768, 1024 and 1280 px. Choose them where your layout breaks, not for specific devices.
Other useful queries
@media (prefers-color-scheme: dark)follows the system dark mode.@media (prefers-reduced-motion: reduce)turns off big animations.@media (hover: hover)targets devices with a mouse.
Fluid tricks that need no breakpoints
font-size: clamp(1rem, 2.5vw, 1.5rem)grid-template-columns: repeat(auto-fit, minmax(250px, 1fr))
💡 Test with DevTools' device toolbar and on a real phone. Touch targets should be at least 44×44 px.
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body { font-family: sans-serif; margin: 0; padding: 16px; }
.cards { display: grid; gap: 12px; }
.card { padding: 20px; border-radius: 12px; background: #eef2ff; }
@media (min-width: 640px) { .cards { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .cards { grid-template-columns: repeat(4, 1fr); } }
@media (prefers-color-scheme: dark) {
body { background: #0f172a; color: #e2e8f0; }
.card { background: #1e293b; }
}
</style>
</head>
<body>
<h1>Resize me 📱💻</h1>
<div class="cards">
<div class="card">1</div><div class="card">2</div>
<div class="card">3</div><div class="card">4</div>
</div>
</body>
</html>