CSSLesson 10 of 10Jump to practice

Responsive design

Make one page work well on phones, tablets and desktops with flexible sizes and media queries.

More than half of all web traffic comes from phones. A responsive page adapts its layout to whatever screen it’s on, instead of making visitors pinch and zoom.

Three things make a page responsive.

1. The viewport tag

From the HTML course. Without it, phones pretend to be a desktop screen and shrink your page.

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

2. Flexible sizes

Avoid fixed widths like width: 960px. Prefer:

  • max-width so things can shrink: max-width: 960px; margin: 0 auto;
  • percentages and fr units
  • rem for text
  • images that never overflow:
img {
  max-width: 100%;
  height: auto;
}

3. Media queries

A media query applies CSS only when a condition is true, usually a minimum screen width.

/* Phones: one column (the default) */
.columns { display: block; }

/* 600px and wider: two columns */
@media (min-width: 600px) {
  .columns {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}

The width at which the layout changes is called a breakpoint.

One column, then two
Open in editor
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: sans-serif; margin: 10px; }
  .columns div { background: #cfeee9; padding: 16px; margin-bottom: 10px; }

  @media (min-width: 500px) {
    .columns {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
    }
    .columns div { margin-bottom: 0; }
  }
</style>
</head>
<body>
<div class="columns">
  <div>On a phone, I'm on top.</div>
  <div>On a wider screen, I'm on the right.</div>
</div>
<p id="width"></p>
<script>
  function show() {
    document.getElementById("width").textContent =
      "This area is " + window.innerWidth + "px wide.";
  }
  show();
  window.addEventListener("resize", show);
</script>
</body>
</html>
Result

Open it in the editor and resize your window across 500px to watch it switch.

Mobile first

Write your base CSS for small screens, then use min-width media queries to add complexity as the screen grows. Phones download only the simple styles they need, and you rarely have to undo anything.

Common breakpoints are around 600px (large phones and small tablets) and 1000px (laptops). Choose yours by where your layout starts to look wrong, not by specific devices.

Practice

Check what you just learned. Fill in the missing code, then answer the quiz.

  1. Exercise 1

    Apply these styles only when the screen is at least 700px wide.

    @media (: 700px) {
      .columns {
        display: flex;
      }
    }

  2. Exercise 2

    Stop images from overflowing narrow screens.

    img {
      : 100%;
      height: auto;
    }

Quiz: 3 questions

1. What does mobile first mean?
2. When does @media (max-width: 600px) apply?
3. Why add height: auto next to max-width: 100% on images?

Finish the practice to complete this lesson.