TutreNews Learn

Layout and responsive design

Responsive design with media queries

Goal: Adapt a layout to different screen sizes with a mobile-first approach · 10 min

A responsive page adapts to phones, tablets and desktops. Three ingredients:

1. The viewport meta tag in the HTML head. Without it, phones pretend to be wide and shrink everything:

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

2. Fluid sizes: use %, fr, rem and max-width instead of fixed pixel widths. Images: img { max-width: 100%; height: auto; }.

3. Media queries change rules at breakpoints:

.cards { display: grid; gap: 1rem; grid-template-columns: 1fr; }

@media (min-width: 600px)  { .cards { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 900px)  { .cards { grid-template-columns: repeat(3, 1fr); } }

Mobile-first means you write the small-screen layout as the default and add min-width queries to enlarge it. It keeps the base CSS simple and loads fast on phones. Choose breakpoints where your content starts to look wrong, not at particular device sizes.

Other useful queries: (prefers-color-scheme: dark) for dark mode, (prefers-reduced-motion: reduce) to switch off animations, print for printing.

Test by resizing the browser window and by using the device toolbar in the browser's developer tools.

Worked example: Which columns at which width?

  1. Base: one column (phones). min-width: 600px → two columns. min-width: 900px → three columns.
  2. At 750px both the base rule and the 600px rule apply; the later, more specific one wins: two columns.
  3. At 1000px all three apply and the last wins: three columns.
.cards { grid-template-columns: 1fr; }
@media (min-width: 600px) {
  .cards { grid-template-columns: repeat(2, 1fr); }
}
@media (min-width: 900px) {
  .cards { grid-template-columns: repeat(3, 1fr); }
}