Responsive Design
More than half of all web traffic comes from mobile devices. Designing only for desktop means half your visitors get a broken experience. Responsive design isn't optional — it's the baseline.
Media Queries
A media query wraps CSS rules so they only apply when a condition is met:
/* Applies on screens 768px wide or wider */
@media (min-width: 768px) {
.sidebar {
display: block;
}
}
/* Applies on screens narrower than 768px */
@media (max-width: 767px) {
.sidebar {
display: none;
}
}
Mobile-First Approach
The best practice is to write your base styles for mobile, then layer on styles for larger screens using min-width queries. This is called mobile-first.
/* Base styles — mobile */
.card-grid {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Tablet — 640px and up */
@media (min-width: 640px) {
.card-grid {
flex-direction: row;
flex-wrap: wrap;
}
}
/* Desktop — 1024px and up */
@media (min-width: 1024px) {
.card-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
}
Mobile-first is better than desktop-first because mobile constraints force you to prioritise content. It also tends to result in less CSS overall — you add complexity as the screen gets larger, rather than stripping it away.
Common Breakpoints
/* Small phones */
@media (min-width: 480px) { ... }
/* Tablets */
@media (min-width: 640px) { ... }
/* Large tablets / small desktops */
@media (min-width: 768px) { ... }
/* Desktops */
@media (min-width: 1024px) { ... }
/* Large desktops */
@media (min-width: 1280px) { ... }
Fluid Typography
Instead of fixed font sizes that feel too small on mobile or too large on desktop, use clamp() for type that scales smoothly:
h1 {
font-size: clamp(1.75rem, 5vw, 3rem);
/* minimum: 1.75rem, preferred: 5% of viewport width, maximum: 3rem */
}
Responsive Images
img {
max-width: 100%;
height: auto;
}
/* Full width on mobile, half width on desktop */
.article-image {
width: 100%;
}
@media (min-width: 768px) {
.article-image {
width: 50%;
float: right;
margin-left: 2rem;
}
}
The Viewport Meta Tag
Always include this in your HTML <head> — without it, mobile browsers zoom out and render your page at desktop width:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Testing Responsiveness
Open your browser's developer tools and click the device toggle icon (or press Cmd+Shift+M in Chrome) to preview your page at different screen sizes. Test at 375px (iPhone), 768px (tablet), and 1280px (desktop) as a minimum.
Have anything to say about this lesson?
Your feedback helps improve these tutorials. If something was confusing or missing, let us know.