Open original
Info
Demo 2.15

Responsive design using @media queries

A media query applies a block of CSS only under certain conditions ~ usually a screen width.

@media (min-width: 600px) {
	.layout {
		grid-template-columns: 200px 1fr;
	}
}

Mobile first

Write the narrow layout first, outside any query. Then add to it as the screen gets bigger, using min-width.

Doing it the other way ~ desktop first, then stripping things away with max-width ~ works, but you end up undoing your own CSS, and phones (the slower devices) do the most work. Pick one direction and stay in it.

Pick breakpoints from your content

There are no correct numbers. Widen the preview until your layout looks bad, and put a breakpoint there. That’s the whole method. Chasing specific device sizes is a losing game ~ there are too many, and they change every year.

Other things you can ask about

  • @media (prefers-color-scheme: dark) ~ the reader has dark mode on.
  • @media (prefers-reduced-motion: reduce) ~ they’ve asked for less animation.
  • @media print ~ styles for printing the page.

And one thing that isn’t CSS

Responsive design needs this line in your HTML <head>:

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

Without it phones pretend to be a desktop and shrink the whole page. All the media queries in the world won’t save you.

The best media query is no media query

clamp(), minmax() and auto-fit handle a lot of what people reach for breakpoints to do. Try those first.

Next chapterJavaScript
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console