Thuta Learning
CSS
AdvancedWeb DevelopmentBeginner

Media Queries

CSSLesson 2830 min

What you'll walk away with

  • Write base styles for phones and add min-width queries for wider screens
  • Predict which rule wins through source order when media queries overlap
  • Use the hover, prefers-color-scheme and prefers-reduced-motion features
  • Explain how a container query differs from a media query

Explain it simply

Explain it simply

A media query is an if statement for CSS. It tells the browser "if the screen is 600px wide or more, use these rules" or "if the user has dark mode on, use these colours". When the condition stops being true, for example when the window is narrowed again, the browser drops those rules immediately.

Think of lights on a sensor: on when it gets dark, off when it gets light. A typical use is showing three cards side by side on a desktop but stacking them on a phone.

Problem → Why → Solution

The problem: why does the phone show two columns?

A developer who started from the desktop design made three columns the base, then added a 600px query for phones and a 900px query for tablets. On a 375px phone the page shows two narrow columns instead of one.

Both queries are valid. The catch is that 375px is "at most 600px" and also "at most 900px". When both match and the selectors have the same specificity, the rule written later wins, and in this file the 900px rule comes last.

.cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

@media (max-width: 600px) {
  .cards { grid-template-columns: 1fr; }
}

/* Written last, so it beats the 600px rule on every phone */
@media (max-width: 900px) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}

A media query adds no specificity

An @media block only switches its rules on or off; it never makes them stronger. Among the rules that are switched on, the normal cascade decides: specificity first, then source order. That is why max-width queries must run from largest to smallest and min-width queries from smallest to largest.

Core concept: rules with conditions

A media query has three parts: @media, a media feature such as (min-width: 600px), and a block of rules that apply only while the condition is true. Width queries measure the viewport, which is why a missing viewport meta tag (previous lesson) makes a phone answer as if it were about 980px wide.

1. Write the base for the narrowest screen

Styles outside any query apply on every screen. Mobile-first makes this base a single column, a layout that works even if no query ever matches.

2. Add with min-width as space grows

@media (min-width: 600px) means "at least 600px". Each query only overrides what has to change, and if you order them from small to large, the last matching (largest) query always wins.

3. Let the content choose breakpoints

Do not chase device widths like 375, 414 or 768. Widen the window slowly and put a breakpoint where two cards comfortably fit or where lines get too long. New devices then need no changes.

4. Ask about more than width

(hover: hover) matches devices whose main input can really hover, like a mouse. (prefers-color-scheme: dark) follows the system dark mode, and (prefers-reduced-motion: reduce) follows the setting for less animation. Users chose these settings themselves, so respect them.

The range syntax (width >= 600px) means the same as min-width: 600px. It can also express a band in one line, such as (400px <= width < 900px), which makes boundaries easier to read. If a project must support quite old browsers, the classic min-width form remains the safest choice.

Media featureWhat it checks
(min-width: 600px)Viewport is 600px or wider
(width >= 600px)Same thing, newer range syntax
(hover: hover)Main input can hover
(prefers-color-scheme: dark)User picked a dark theme
(prefers-reduced-motion: reduce)User asked for less motion
Mental model: a staircase that only goes up
  1. Write the base for phones
  2. Find the width where content breaks
  3. Override only what changes
  4. Order queries from small to large
  5. Add the user-preference queries

As the screen widens you climb one step at a time, each step adding a few rules. No step should have to undo the one below it.

General pattern

css
.component { /* base: narrowest screens */ }

@media (min-width: BREAKPOINT) {
  .component { /* only what changes when there is room */ }
}

@media (feature: value) {
  .component { /* user preference or device capability */ }
}

Keep the base rule outside any query, order width breakpoints from small to large, and usually place feature queries such as hover, colour scheme and motion after the layout queries.

A mobile-first card grid

This grid is written mobile-first, 1 → 2 → 3 columns: one column by default, then min-width queries widen it, instead of starting from a desktop 3 → 2 → 1 layout and undoing it with max-width. It also adds a hover effect, reduced motion and dark mode. Run it and change the preview width; switch your system to dark mode and the colours follow.

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Mobile-first cards</title>
  <style>
    body { margin: 0; padding: 16px; font-family: system-ui, sans-serif; }

    /* Base: written for the narrowest screen, one column */
    .cards {
      display: grid;
      grid-template-columns: 1fr;
      gap: 16px;
    }

    .card {
      padding: 16px;
      border: 1px solid #cbd5e1;
      border-radius: 12px;
      transition: transform 0.2s ease;
    }

    /* Room for two cards side by side */
    @media (min-width: 600px) {
      .cards { grid-template-columns: repeat(2, 1fr); }
    }

    /* Room for three */
    @media (min-width: 900px) {
      .cards { grid-template-columns: repeat(3, 1fr); }
    }

    /* Only devices that can really hover get the lift */
    @media (hover: hover) {
      .card:hover { transform: translateY(-4px); }
    }

    @media (prefers-reduced-motion: reduce) {
      .card { transition: none; }
    }

    @media (prefers-color-scheme: dark) {
      body { background: #0f172a; color: #e2e8f0; }
      .card { border-color: #334155; }
    }
  </style>
</head>
<body>
  <div class="cards">
    <article class="card">Starter plan</article>
    <article class="card">Pro plan</article>
    <article class="card">Team plan</article>
  </div>
</body>
</html>

Code breakdown

  1. Mobile basegrid-template-columns: 1fr;

    The base rule with no query. Every screen starts here, and phones simply keep it.

  2. First step up@media (min-width: 600px) {

    From 600px up the grid gets two columns. Display and gap are not repeated; only the columns change.

  3. Second step up@media (min-width: 900px) {

    At 1000px both queries match; this one comes later, so it wins and the grid has three columns. It is the mirror image of the bug in the problem section.

  4. Hover only where hover exists@media (hover: hover) {

    On touch screens a :hover style can stay stuck after a tap. This query gives the lift only to devices with a real hover input such as a mouse.

  5. Respect reduced motion@media (prefers-reduced-motion: reduce) {

    If the user turned on reduced motion in their system settings, the transition is removed: the card still moves on hover, but instantly, without animation.

You should see
Up to 599px: the three cards are stacked.
600-899px: two cards side by side, the third below.
900px and wider: all three in one row.
With a mouse, a hovered card lifts by 4px; in dark mode the background turns dark navy.

Container queries: when a component asks about its own space

A media query only asks about the viewport. Put the same card component in a wide main area and in a narrow sidebar: the viewport is identical, but the space each card gets is completely different. Container queries solve this. Declare the parent a container with container-type: inline-size, then ask about that parent's width with @container (min-width: 400px).

Two details matter. The query can only style the container's descendants, never the container itself. And an element with inline-size containment no longer sizes itself from its content, so in a shrink-to-fit context it can collapse. Container queries are supported in current versions of all major browsers.

.card-slot { container-type: inline-size; }

/* Stacked by default */
.card { display: grid; gap: 12px; }

/* Side-by-side once the slot itself is at least 400px wide */
@container (min-width: 400px) {
  .card { grid-template-columns: 120px 1fr; }
}

In real projects

In real projects

Most projects have only three or four width breakpoints, listed once as custom properties or Sass variables. The sm:, md: and lg: prefixes in frameworks such as Tailwind are min-width media queries underneath, which makes them mobile-first; this lesson is the key to reading those classes.

Preference queries matter in production too. Many sites support a dark theme through prefers-color-scheme by swapping a handful of custom properties. Most animation libraries check prefers-reduced-motion and switch off parallax and auto-playing effects. Dropdown menus that open on click or tap, not only on hover, keep touch users from getting stuck. Design-system components are gradually moving to container queries so they work wherever they are dropped: a sidebar, a modal or a grid cell.

Common mistakes

Common mistakes

Ordering queries the wrong way round

As the problem section showed, sorting max-width queries from small to large lets the wide query win on narrow screens too. No error appears, so it is hard to find. In the DevTools Styles panel, the crossed-out rule shows exactly which rule was overridden and by whom.

Overlapping boundaries

Pairing @media (max-width: 600px) with @media (min-width: 600px) means both match at exactly 600px, which can produce a strange layout at that one width. Using only min-width, mobile-first, removes the problem; if you need both, range syntax like (width < 600px) makes the boundary explicit.

Relying on hover alone

A menu or tooltip shown only on :hover is unreachable for touch-screen and keyboard users. Treat hover as decoration inside (hover: hover) and make important content reachable through :focus-visible or a click as well.

Mini challenge

A mobile-first course page layout

Write a mobile-first page with a nav inside a header, a main course list and an aside with filters. On a phone everything stacks; as space grows the nav turns horizontal, and finally main and aside sit side by side. Support dark mode as well.

  • In the base styles, .layout is a one-column grid and the nav links are vertical
  • At @media (min-width: 700px) the nav links sit in one row
  • At @media (min-width: 960px) main and aside become two columns, 1fr 260px, with the header spanning both
  • Under prefers-color-scheme: dark, the background and text colours change
layout.css
/* Markup: .layout > header > nav.nav > a*3, then main, then aside */

.layout {
  /* TODO: one-column grid with a gap and some padding */
}

.nav {
  /* TODO: vertical flex column */
}

/* TODO: at 700px and up, nav links in a row */

/* TODO: at 960px and up, main + aside side by side (1fr 260px) */
/* TODO: make the header span every column */

/* TODO: dark colours when the user prefers a dark scheme */

Expected: 375px: three vertical nav links, aside below main. 800px: the nav links in one row, main and aside still stacked. 1024px: main wide on the left, aside 260px on the right.

Show hint

Use grid-column: 1 / -1 to make the header span every column. The nav only needs flex-direction to change from column to row. Put the 700 query before the 960 one.

Show solution
course-page.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { margin: 0; font-family: system-ui, sans-serif; color: #111827; }

    .layout { display: grid; gap: 16px; padding: 16px; }
    .nav { display: flex; flex-direction: column; gap: 8px; }
    .nav a { padding: 12px; border-radius: 8px; background: #e0e7ff; color: inherit; }

    @media (min-width: 700px) {
      .nav { flex-direction: row; }
    }

    @media (min-width: 960px) {
      .layout { grid-template-columns: 1fr 260px; }
      .layout header { grid-column: 1 / -1; }
    }

    @media (prefers-color-scheme: dark) {
      body { background: #0f172a; color: #e2e8f0; }
      .nav a { background: #1e293b; }
    }
  </style>
</head>
<body>
  <div class="layout">
    <header>
      <nav class="nav">
        <a href="#">Home</a><a href="#">Courses</a><a href="#">About</a>
      </nav>
    </header>
    <main>Course list</main>
    <aside>Filters</aside>
  </div>
</body>
</html>

Quick quiz 1 / 3

With the CSS from the problem section (base 3 columns, then the max-width: 600px rule, then the max-width: 900px rule), how many columns appear at a 500px viewport?

Quick quiz 2 / 3

In a mobile-first stylesheet, which screens are the base rules outside any media query written for?

Quick quiz 3 / 3

Which query should wrap a :hover effect so it does not get stuck after a tap on a touch screen?

What to remember

  • A media query only switches rules on or off; when queries overlap, source order decides
  • Mobile-first: write the base for phones and order min-width queries from small to large
  • Pick breakpoints where the content breaks, not from a list of devices
  • Respect devices and users with hover, prefers-color-scheme and prefers-reduced-motion
  • Use a container query when a component should respond to its own space

Responsive web design — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Media Queries | Thuta Learning