CSS Basics · Lesson 10 of 11

Responsive Design

People will open your page on a phone, a laptop and everything in between. A responsive page changes its layout to fit the screen it is on.

The tool for that is the media query: a block of CSS that only applies when a condition is true.

.columns {
  display: flex;
  gap: 20px;
}

@media (max-width: 600px) {
  .columns {
    flex-direction: column;
  }
}

Read it as: when the screen is 600 pixels wide or less, use these rules as well. Here, two columns that sit side by side on a wide screen stack on top of each other on a phone. flex-direction: column turns a flex row into a vertical stack.

  • max-width: 600px matches screens up to 600 pixels wide.
  • min-width: 601px matches screens from 601 pixels wide.

The rules inside the query are written exactly like normal rules, one level deeper. Put media queries after the normal rules they change, because when two rules disagree the later one wins.

The viewport tag

For media queries to work on real phones, the page's head needs this line. Without it, phones pretend to be a wide screen and shrink everything:

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

To test it here, make your browser window narrower, or turn your phone sideways and back. The preview follows the width of its own panel.

Your Task

  1. Add a media query for screens up to 600px wide.
  2. Inside it, change .columns to flex-direction: column.
  3. Also inside it, reduce the h1 to a font-size of 24px.
  • There is a media query for a maximum width of 600px
  • Inside it, .columns gets flex-direction: column
  • Inside it, h1 gets a font size of 24px
  • The normal rules outside the query are still there