What is a media query?

A media query applies CSS only when a condition about the device or user environment is true, such as the viewport width, orientation, the user's color scheme or motion preference, or the input type. It is written with @media, for example @media (min-width: 768px) { ... }, and is the core tool of responsive design.

Common features

  • Size: (min-width: 768px), (max-width: 600px), or the range syntax (width >= 768px), (600px <= width < 1024px).
  • (orientation: landscape), (aspect-ratio: 16/9).
  • User preferences: (prefers-color-scheme: dark), (prefers-reduced-motion: reduce), (prefers-contrast: more).
  • Input: (hover: hover) and (pointer: coarse) distinguish mouse from touch.
  • Media types: screen, print (@media print for print styles).
  • Combine with and, , (or) and not.

Using them in other places

  • HTML: <link rel="stylesheet" media="print">, <source media="..."> in <picture>.
  • JavaScript: window.matchMedia("(prefers-color-scheme: dark)") with a change listener.

Media queries vs container queries

Media queries respond to the viewport; container queries (@container (min-width: 400px)) respond to the size of a parent element, making components reusable in any layout slot.

Best practices

  • Write mobile-first min-width queries.
  • Choose breakpoints where the content breaks, not for specific devices.
  • Use em/rem in queries so they respect user zoom and font settings.
  • Fluid techniques (clamp(), Grid auto-fill) reduce how many queries you need.

Code example

html
1<style>
2 body { font-family: system-ui; margin: 0; padding: 12px; }
3 .layout { display: grid; gap: 10px; }
4 .layout div { border: 2px solid #0b1020; padding: 12px; border-radius: 8px; background: #dbeafe; }
5 /* Mobile first: one column, then more as space allows */
6 @media (width >= 600px) { .layout { grid-template-columns: 1fr 1fr; } }
7 @media (width >= 900px) { .layout { grid-template-columns: repeat(3, 1fr); } }
8 @media (prefers-color-scheme: dark) {
9 body { background: #0b1020; color: white; }
10 .layout div { background: #1e293b; border-color: white; }
11 }
12 @media (hover: hover) { .layout div:hover { transform: translateY(-2px); } }
13 @media print { .no-print { display: none; } }
14</style>
15<p class="no-print">Resize the window; this line is hidden when printing.</p>
16<div class="layout"><div>One</div><div>Two</div><div>Three</div></div>
17<p id="out"></p>
18<script>
19 const mq = matchMedia("(width >= 600px)");
20 const show = () => (document.getElementById("out").textContent = mq.matches ? "Wide layout" : "Narrow layout");
21 mq.addEventListener("change", show);
22 show();
23</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app