EMZETT.
Login

Media queries and breakpoints: Adapting layout to screens

In short: With media queries CSS applies rules only under certain conditions, such as from a screen width; this adapts a page to phone, tablet and desktop.

In more detail: A responsive page looks good on every device. A prerequisite is <meta name="viewport" content="width=device-width, initial-scale=1"> in the HTML so that mobile browsers use the real width.

In Depth

Syntax and mobile-first

.card { display: block; }            /* default: phone */
 
@media (min-width: 768px) {
  .card { display: flex; gap: 1rem; } /* from tablet */
}
@media (min-width: 1200px) {
  .card { max-width: 1100px; }        /* from desktop */
}

Mobile-first: write the layout for small screens first, then add with min-width for larger ones. This is usually simpler and loads less unnecessary stuff on the phone.

Typical breakpoints

About 640 px (large phone), 768 px (tablet), 1024 px (small laptop), 1280 px (desktop). Align breakpoints to the content: where does the layout break? Set one there. Use relative units (rem, %, vw) and clamp() for fluid font sizes: font-size: clamp(1rem, 2.5vw, 1.5rem);.

Other queries

  • prefers-color-scheme: dark: the system’s dark mode.
  • prefers-reduced-motion: reduce: reduce animations (accessibility).
  • orientation: landscape, print for printing.
  • hover: hover and pointer: coarse: mouse versus touch.
  • Container queries (@container) react to the size of the surrounding element instead of the window, ideal for reusable components.

Checking and pitfalls

Test with the device icons of the browser developer tools (F12) and on real devices. Avoid fixed pixel widths, horizontal scrolling and too small tap targets (at least about 44 px). Adapt images with max-width: 100% and srcset. Flexbox and Grid solve a lot even without media queries (flex-wrap, repeat(auto-fit, minmax(...))).

See also: WCAG and colour contrast