← Web basics: HTML, CSS and JavaScript

Responsive design

One page that works on phones, tablets and big screens.

Start this lesson

People visit the same page on a small phone and a wide monitor. Responsive design means the page adapts. Three habits do most of the work. First, add the viewport meta tag in the head, so phones show the page at its real width instead of a shrunken desktop view. Second, use flexible sizes: percentages, max-width, and images with max-width: 100% so they never overflow. Third, use media queries: CSS rules that only apply when a condition is true, such as "the screen is at least 700px wide".

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

img {
  max-width: 100%;
}
.cards {
  display: flex;
  flex-direction: column;
}
@media (min-width: 700px) {
  .cards {
    flex-direction: row;
  }
}

On narrow screens the cards stack in a column. Once the screen is 700px or wider, the media query switches them to a row. Images shrink to fit their container.

Writing the phone layout first and adding min-width media queries for bigger screens is called "mobile first". It keeps the simple layout as the default.

max-width queries do the opposite: @media (max-width: 600px) { ... } applies only on screens 600px wide or less.