Course outline · 0% complete

0/30 lessons0%

Course overview →

Media queries and mobile-first

lesson 7-2 · ~9 min · 22/30

One page, every screen

More than half of all web traffic comes from phones, so a layout that only works at desktop width fails most visitors — and there is no separate "mobile version" of your CSS file. One stylesheet must adapt itself, and media queries are the mechanism.

A media query applies CSS only while a condition about the device is true:

.cards {
  display: grid;
  grid-template-columns: 1fr; /* phones: one column */
}

@media (min-width: 640px) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}

@media (min-width: 1024px) {
  .cards { grid-template-columns: repeat(3, 1fr); }
}

Read @media (min-width: 640px) as: at 640px wide and up. The widths where the layout changes (640, 1024) are called breakpoints.

Writing base rules for the smallest screen, then layering desktop upgrades on with min-width queries, is called mobile-first, and it is the standard approach. Phone layouts are the simple ones, so enhancing upward beats gutting downward.

The tag that makes it all work

One line in your head (part of the lesson 2-1 skeleton family), or phones will pretend to be 980px-wide desktops and shrink everything to fit:

<meta name="viewport" content="width=device-width, initial-scale=1">

It tells the browser to make the layout viewport match the device's real width at 100% zoom. Every responsive page needs it. Skip it and your carefully written media queries never even fire on phones, because the browser lies about its width.

Testing without a drawer full of phones: DevTools has a device toolbar that resizes the viewport freely. You will meet it properly in lesson 9-1.

Quiz

In mobile-first CSS, the rules written OUTSIDE any media query target which screens?

Code exercise · javascript

Implement the breakpoint logic from the .cards example as a function. pickColumns(width) returns 1 below 640px, 2 from 640px, and 3 from 1024px. Mind the boundaries: min-width means "at this value and up".

Problem

Your media queries work in desktop DevTools but a real phone still shows a shrunken desktop layout. Which head tag is missing?