Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.2 — Media Queries
CSS · Example 2 of 4

Testing media queries from JavaScript

These lines give the same answer on every screen, so they are safe to print. An invalid query doesn't throw: it simply never matches. That's also what happens to a CSS @media block with a typo: its rules silently never apply.

A media query wraps rules in a condition about the device, such as @media (min-width: 40rem) { ... }, so they apply only when it's true; you can test width ranges with min-/max- or the newer range syntax, test orientation, and combine tests with and, commas and not.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make .sidebar hidden on screens narrower than 48rem and shown as a 16rem-wide column on wider screens, mobile first, with range syntax.

02

Write one media query that applies when the screen is in landscape and at most 500px tall (a phone on its side), and reduce the header's padding there.

03

In JavaScript, log "wide" or "narrow" now, and again every time the viewport crosses 48rem.

Explain it without notes

01

What is a media query, and what happens to the rules inside it?

02

Explain min-width vs max-width and why mobile-first code mostly uses min-width.

03

What problem does the range syntax solve?

04

How do you combine media queries with "and", "or" and "not"?

05

Why can a rule inside a matching media query still lose?

Testing media queries from JavaScript

Console

(nothing was printed)

Expected console output

all -> true
screen -> true
print -> false
(min-width: 0px) -> true
(width >= 100000px) -> false
not print -> true
print, (min-width: 0px) -> true
invalid query matches? false