Your website will be opened on a 5-inch phone held in one hand, a 13-inch laptop, a 27-inch monitor, a tablet turned sideways, and sometimes even printed on paper. Building a separate site for each of them is impossible. Instead, we build one site whose layout adapts to whatever screen it lands on.
That approach is called responsive web design, and its most important tool is the media query. In this chapter we learn the viewport meta tag, fluid layouts and images, the full media query syntax (including the modern range syntax), the mobile-first strategy, how to choose breakpoints, and the user-preference queries for dark mode, reduced motion and printing.
What is Responsive Design?
Responsive web design is the practice of building a single page whose layout, sizes and content adapt to the size and capabilities of the device displaying it, instead of serving separate fixed-width designs.
The term was coined by Ethan Marcotte in 2010. He described three ingredients, and they are still the foundation today:
Fluid layouts: widths in relative units (
%,fr, flexible flex items) instead of fixed pixels.Flexible media: images and videos that shrink with their container.
Media queries: CSS that applies only when certain conditions (like screen width) are true.
Modern CSS adds a fourth ingredient: layouts that adapt by themselves, like flex-wrap and the auto-fit card grid from Grid Layout Patterns. A good responsive site uses intrinsic layouts wherever possible and media queries for the bigger structural changes.
Step 0: The Viewport Meta Tag
Before any CSS, every responsive page needs this line in its <head>:
<meta name="viewport" content="width=device-width, initial-scale=1">
Why? When smartphones arrived, most websites were designed for desktops around 1000px wide. So mobile browsers pretend the screen is wide (typically 980px), lay the page out at that width, and then shrink the whole thing to fit. Text becomes tiny and the user has to pinch-zoom.
Without the meta tag With the meta tag
┌──────────────┐ ┌──────────────┐
│ tiny desktop │ layout width │ Readable │ layout width
│ page shrunk │ ≈ 980px, scaled │ text, mobile │ = device width
│ to fit │ down │ layout │ (e.g. 390px)
└──────────────┘ └──────────────┘
width=device-width: make the layout viewport as wide as the device's screen in CSS pixels.initial-scale=1: start at 100% zoom.
Without this tag, your media queries won't fire as expected on phones, because the browser reports the fake 980px width. Don't add maximum-scale=1 or user-scalable=no: blocking zoom hurts users with low vision.
Fluid Layouts and Flexible Images
A fixed-width layout breaks on small screens:
/* ❌ forces horizontal scrolling on any screen narrower than 960px */
.container {
width: 960px;
}
/* ✅ fluid: full width on small screens, capped and centred on large ones */
.container {
max-width: 960px;
margin-inline: auto;
padding-inline: 1rem;
}
Images are a classic culprit too. An 1200px-wide photo inside a 360px phone column overflows. One rule fixes it for the whole site:
img,
video {
max-width: 100%; /* never wider than the container */
height: auto; /* keep the aspect ratio */
}
max-width (not width) means a small image is never stretched up, only large ones are scaled down. To send smaller files to small screens, use the HTML srcset and sizes attributes or the <picture> element; CSS can only scale the image, not change which file is downloaded.
Media Query Syntax
A media query is a condition about the device or environment (its type, viewport size, orientation, user preferences, and so on). CSS inside an
@mediarule is applied only while that condition is true, and is re-evaluated whenever the condition changes, for example when the window is resized.
@media media-type and (media-feature) {
/* rules applied only when the query matches */
}
/* example */
@media screen and (min-width: 768px) {
.sidebar {
display: block;
}
}
Media types
| Type | Matches |
|---|---|
all | Every device (the default when no type is given) |
screen | Screens: phones, tablets, laptops, monitors |
print | Printing and print preview / "Save as PDF" |
Older types such as handheld, tv and projection are deprecated and match nothing in modern browsers. In practice you usually omit the type (@media (min-width: 768px)) and only write print when targeting printers.
Common media features
| Feature | Example | Use |
|---|---|---|
width (with min-/max- or ranges) | (min-width: 768px) | Layout breakpoints (viewport width) |
height | (max-height: 500px) | Short screens, e.g. phones in landscape |
orientation | (orientation: landscape) | landscape when width > height; otherwise portrait (a square viewport counts as portrait) |
hover | (hover: hover) | The primary input can hover (mouse, trackpad) |
pointer | (pointer: coarse) | Primary input is imprecise (finger) → bigger tap targets |
prefers-color-scheme | (prefers-color-scheme: dark) | User chose a dark theme in the OS |
prefers-reduced-motion | (prefers-reduced-motion: reduce) | User asked the OS for less animation |
resolution | (min-resolution: 2dppx) | High-density ("retina") screens |
Combining conditions
| Operator | Meaning | Example |
|---|---|---|
and | All conditions must be true | (min-width: 600px) and (orientation: landscape) |
, (comma) | OR: any of the queries may be true | (max-width: 600px), print |
or | OR inside a condition (Media Queries Level 4) | (width < 600px) or (orientation: portrait) |
not | Negates the whole query (a type is needed in the old syntax) | not print, not all and (hover: hover) |
only | Hides the query from very old browsers; no effect today | only screen and (min-width: 768px) |
The modern range syntax
The min-/max- prefixes are confusing ("min-width" means "width is at least"). Media Queries Level 4 lets you write real comparisons:
/* old style */
@media (min-width: 768px) { … }
@media (max-width: 767px) { … }
@media (min-width: 768px) and (max-width: 1023px) { … }
/* range syntax: same meaning, easier to read */
@media (width >= 768px) { … }
@media (width < 768px) { … }
@media (768px <= width < 1024px) { … }
The range syntax has worked in Chrome and Edge 104, Firefox 102 and Safari 16.4 onwards, and is Baseline: widely available, so it is safe to use. It also fixes a subtle bug. With max-width: 767px and min-width: 768px, a viewport of 767.5px (possible with browser zoom or high-density screens) matches neither query. With width < 768px and width >= 768px there is no gap.
Note that min-width: 768px is inclusive: it is the same as width >= 768px, not width > 768px.
Mobile-First vs Desktop-First
There are two ways to organise media queries.
/* MOBILE-FIRST: base styles for small screens,
then add complexity as space grows (min-width / width >=) */
.cards { grid-template-columns: 1fr; }
@media (width >= 600px) {
.cards { grid-template-columns: repeat(2, 1fr); }
}
/* DESKTOP-FIRST: base styles for large screens,
then undo things as space shrinks (max-width / width <) */
.cards { grid-template-columns: repeat(3, 1fr); }
@media (width < 600px) {
.cards { grid-template-columns: 1fr; }
}
| Mobile-first | Desktop-first | |
|---|---|---|
| Base CSS targets | Smallest screens | Largest screens |
| Queries use | min-width / width >= | max-width / width < |
| Media queries mostly | Add layout (columns, sidebars) | Undo layout |
| Phones apply | Just the simple base styles | Desktop styles, then overrides that undo them |
| Recommended? | Yes, the usual industry default | Fine for retrofitting old desktop sites |
Mobile-first usually means less CSS overall: a single-column layout needs almost no code (block elements already stack), so the base is small, and each query adds only what bigger screens need. It also forces you to decide what content really matters.
A Complete Mobile-First Example
A header with navigation and a set of cards. On phones the links stack and cards are in one column; on tablets the nav becomes a row and cards form two columns; on desktops there are three columns.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="site-header">
<nav class="nav">
<a href="#">Home</a>
<a href="#">Courses</a>
<a href="#">Contact</a>
</nav>
</header>
<main class="cards">
<article class="card">Card 1</article>
<article class="card">Card 2</article>
<article class="card">Card 3</article>
</main>
</body>
</html>
* { box-sizing: border-box; }
body {
margin: 0;
font-family: system-ui, sans-serif;
}
/* ---------- base = phones ---------- */
.site-header {
background: #1e3a8a;
color: white;
padding: 1rem;
}
.nav {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.nav a { color: white; }
.cards {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
padding: 1rem;
}
.card {
border: 1px solid #ccc;
border-radius: 8px;
padding: 1rem;
}
/* ---------- tablets and up ---------- */
@media (width >= 600px) {
.nav {
flex-direction: row;
gap: 1.5rem;
}
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
/* ---------- desktops ---------- */
@media (width >= 900px) {
.cards {
grid-template-columns: repeat(3, 1fr);
max-width: 1100px;
margin-inline: auto;
}
}
What you see when resizing the browser (checked in Chrome):
width < 600px 600px – 899px ≥ 900px
┌──────────────┐ ┌──────────────────────┐ ┌─────────────────────────────┐
│ Home │ │ Home Courses Contact│ │ Home Courses Contact │
│ Courses │ ├──────────────────────┤ ├─────────────────────────────┤
│ Contact │ │ ┌────────┐┌────────┐ │ │ ┌───────┐┌───────┐┌───────┐ │
├──────────────┤ │ │ Card 1 ││ Card 2 │ │ │ │Card 1 ││Card 2 ││Card 3 │ │
│ ┌──────────┐ │ │ └────────┘└────────┘ │ │ └───────┘└───────┘└───────┘ │
│ │ Card 1 │ │ │ ┌────────┐ │ └─────────────────────────────┘
│ └──────────┘ │ │ │ Card 3 │ │
│ ┌──────────┐ │ │ └────────┘ │
│ │ Card 2 │ │ └──────────────────────┘
│ └──────────┘ │
│ Card 3 … │
└──────────────┘
Notice that the desktop query only adds what changes. It doesn't repeat the nav rules, because the 600px query still matches at 900px and above: media queries stack.
Rearranging a grid layout
Named areas from the CSS Grid chapter make bigger layout changes painless. Here is the holy grail page from Grid Layout Patterns, now mobile-first:
.page {
display: grid;
gap: 1rem;
grid-template-areas:
"header"
"nav"
"main"
"ads"
"footer";
}
@media (width >= 900px) {
.page {
grid-template-columns: 200px 1fr 200px;
grid-template-areas:
"header header header"
"nav main ads"
"footer footer footer";
}
}
The HTML and the grid-area assignments don't change at all; only the drawing does.
Media Queries and the Cascade
A media query adds no specificity. It only switches its rules on or off. Once switched on, those rules compete normally using the rules from Specificity, Inheritance & the Cascade. So order matters:
/* ❌ media query first: the later base rule wins at every width */
@media (width >= 600px) {
.title { font-size: 2rem; }
}
.title { font-size: 1.5rem; }
/* ✅ base rule first, query after it */
.title { font-size: 1.5rem; }
@media (width >= 600px) {
.title { font-size: 2rem; }
}
In the first version both selectors are .title (same specificity), so the one that comes later wins, and the larger size is never seen. Also watch out for a more specific selector in the base styles: .header .title in the base beats a plain .title inside the query, wherever they appear.
Choosing Breakpoints
A breakpoint is a viewport width at which a media query switches the layout.
Beginners often pick breakpoints from device lists ("iPhone is 390px, iPad is 768px"). There are thousands of devices, and new sizes appear every year. The better rule is:
Let the content decide. Start with the narrow layout, widen the browser slowly, and add a breakpoint where the design starts to look bad: lines get too long, cards become too wide, or there is enough room for a sidebar.
Still, it helps to know common reference values used by popular frameworks:
| Framework | Breakpoints (min-width) |
|---|---|
| Tailwind CSS | sm 640px, md 768px, lg 1024px, xl 1280px, 2xl 1536px |
| Bootstrap 5 | sm 576px, md 768px, lg 992px, xl 1200px, xxl 1400px |
Two or three breakpoints are enough for most sites. If you need many more, that is usually a sign that intrinsic techniques (wrapping flex items, auto-fit grids, fluid type) could do the job instead.
px or em in media queries?
Inside a media query, em and rem are based on the browser's initial font size (normally 16px), not on any font-size you set on html. We confirmed this in Chrome: with html { font-size: 20px; }, (min-width: 40em) still switched at 640px (40 × 16), not 800px. If a user raises their default font size to 20px in browser settings, though, 40em becomes 800px, so em breakpoints adapt to the user's text size. Both units are acceptable; many teams use px for simplicity and some prefer em for this accessibility reason.
Fluid Typography in One Line
Instead of changing font-size at every breakpoint, you can let it scale smoothly with the viewport, within limits:
h1 {
font-size: clamp(1.75rem, 1rem + 3vw, 3rem);
}
clamp(MIN, PREFERRED, MAX) uses the preferred value but never goes below the minimum or above the maximum. Worked example with 1rem = 16px:
viewport 375px: 16 + 3% of 375 = 16 + 11.25 = 27.25px → below 28px min → 28px
viewport 800px: 16 + 3% of 800 = 16 + 24 = 40px → within range → 40px
viewport 1400px: 16 + 3% of 1400 = 16 + 42 = 58px → above 48px max → 48px
Mixing rem into the preferred value keeps text zoomable (a pure vw size ignores browser zoom settings). We explore clamp() more in Modern CSS: :has(), Nesting, clamp() & Logical Properties.
Queries for User Preferences
Responsive design is not only about width. Users tell the operating system what they prefer, and CSS can listen.
Dark mode
body {
background: white;
color: #111;
}
@media (prefers-color-scheme: dark) {
body {
background: #111;
color: #eee;
}
}
Writing every colour twice gets tiring on a big site. In CSS Variables (Custom Properties) we will define each colour once as a variable and only switch the variables inside this query.
Reduced motion
Big animations can make some people dizzy or nauseous (for example, people with vestibular disorders). Respect their setting:
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
This is a common "safety net" rule. Transitions and animations themselves are covered in later chapters.
Touch vs mouse
/* only show hover effects where hovering is actually possible */
@media (hover: hover) {
.card:hover { box-shadow: 0 4px 12px rgb(0 0 0 / 0.2); }
}
/* bigger tap targets for fingers */
@media (pointer: coarse) {
.nav a { padding: 0.75rem 1rem; }
}
On touch screens, a :hover style can "stick" after a tap. Wrapping hover effects in (hover: hover) avoids that. Note that a narrow window does not mean touch: a laptop can be narrow and a tablet with a keyboard can be wide, so test the input capability, not the width.
Print Styles
Students print notes; companies print invoices. A small print stylesheet makes that pleasant:
@media print {
nav,
.sidebar,
.ads,
footer {
display: none; /* hide what's useless on paper */
}
body {
color: black;
background: white;
font-size: 12pt; /* pt is a natural unit for paper */
}
a[href^="http"]::after {
content: " (" attr(href) ")"; /* print the URL next to external links */
}
}
Test it with the browser's print preview (Ctrl + P), or in Chrome DevTools with the "Emulate CSS media type: print" option in the Rendering panel.
Other Ways to Use Media Queries
<!-- load a whole stylesheet only for print -->
<link rel="stylesheet" href="print.css" media="print">
/* inside an @import */
@import url("wide.css") screen and (width >= 1200px);
A <link> with a non-matching media attribute is still downloaded (with low priority), but it doesn't block the page from rendering. And from JavaScript, window.matchMedia("(width >= 768px)").matches tells you whether a query currently matches.
Testing Responsive Designs
Resize the browser window slowly from narrow to wide and watch for breakage.
Chrome/Edge DevTools device mode (Ctrl + Shift + M) simulates phone sizes, touch input and pixel density.
Test on at least one real phone. Emulators don't show real finger sizes, the mobile address bar, or performance on cheaper devices.
Look for horizontal scrolling: it usually means something has a fixed width or an unbreakable long word.
Common Mistakes
Forgetting the viewport meta tag. Phones then lay the page out around 980px wide and your queries seem broken.
Putting media queries before the base rules. Equal-specificity base rules later in the file override them.
Overlapping or gapped ranges like
max-width: 768pxtogether withmin-width: 768px(both match at exactly 768px). Usewidth < 768pxandwidth >= 768px.Fixed widths on containers, images or tables that cause horizontal scrolling.
Breakpoints for specific devices instead of where the content breaks.
Assuming small screen = touch. Use
hoverandpointerfor input capabilities.Disabling zoom with
user-scalable=no: an accessibility failure.
Interview & Exam Questions
1. What does <meta name="viewport" content="width=device-width, initial-scale=1"> do, and what happens without it?
It tells mobile browsers to set the layout viewport width to the device's width in CSS pixels and start at 100% zoom. Without it, mobile browsers lay the page out at a wide virtual viewport (typically 980px) and scale it down, so text is tiny and width-based media queries see the wrong width.
2. Explain mobile-first design. Why is it preferred?
You write base styles for the smallest screens and use min-width (or width >=) queries to add layout as space grows. It's preferred because simple, stacked layouts need little CSS, small devices aren't burdened with complex overrides, and it makes you prioritise content.
3. Does a rule inside @media have higher specificity than one outside?
No. Media queries add no specificity; they only decide whether their rules apply. If the selectors have equal specificity, whichever comes later in the source wins, which is why media queries are normally written after the base rules.
4. With html { font-size: 20px; } and default browser settings, at what width does @media (min-width: 50em) start matching?
At 800px. em in media queries is based on the initial font size (16px by default), not on the page's html font size, so 50 × 16 = 800px.
5. What is the difference between (min-width: 600px) and (width > 600px)?
min-width: 600px is inclusive: it means width ≥ 600px. width > 600px excludes exactly 600px. The range form width >= 600px is the exact equivalent of min-width: 600px.
6. Compute the font size of clamp(1rem, 0.5rem + 2vw, 2rem) at a 1000px viewport (1rem = 16px).
Preferred = 8 + 2% of 1000 = 8 + 20 = 28px. Min = 16px, max = 32px. 28px is within the range, so the result is 28px.
Summary
Responsive design = fluid layouts + flexible media + media queries, plus intrinsic layouts that adapt on their own.
Always include the viewport meta tag.
Use
max-width: 100%; height: auto;for images andmax-width+ auto margins for containers.@mediaapplies rules conditionally: media types (screen,print), features (width,orientation,hover,pointer,prefers-*) and operators (and, comma,or,not).The range syntax (
width >= 768px) is widely available, easier to read and avoids gaps between ranges.Prefer mobile-first; let content choose breakpoints; place queries after base rules (they add no specificity).
Respect user preferences: dark mode, reduced motion, print.
Media queries always ask about the viewport. But a component (say, a product card) may sit in a wide main column on one page and a narrow sidebar on another, at the same viewport width. For that, CSS has a newer tool: Container Queries, our next chapter.