11. Responsive Design

People view websites on phones, tablets and large screens, so a page must adapt. A responsive page uses flexible widths (percentages, max-width), flex-wrap, and media queries. A media query applies CSS only when a condition is true, such as the screen being narrower than 600px. In a real page you also add the viewport meta tag to the head so phones do not zoom the page out.

Key points

  • Add <meta name="viewport" content="width=device-width, initial-scale=1"> to every page.
  • Design for a small screen first, then add rules for larger screens.
  • Use max-width: 100% on images so they never overflow.
  • Test by resizing your browser window.

Example: A media query

HTML and CSS Open in editor
<div class="row">
  <div class="card">One</div>
  <div class="card">Two</div>
  <div class="card">Three</div>
</div>

<style>
  .row { display: flex; gap: 12px; }
  .card { flex: 1; border: 2px solid black; padding: 20px; text-align: center; }

  /* On narrow screens, stack the cards */
  @media (max-width: 500px) {
    .row { flex-direction: column; }
  }
</style>
Show explanation

On a wide screen the cards sit side by side. When the preview is narrower than 500px they stack. Drag your browser window narrower to see it.

Try it yourself

Edit the code below and press Run. The result appears in the preview underneath.

Editor
Reset Preview runs in a safe sandbox. Scripts are disabled.
PREVIEW