🎓 A1Learner
🔍
0 of 54 lessons completed

CSS Media Queries

A media query applies a block of styles only when the page matches a condition. The usual condition is the width of the viewport, the area the page is shown in.

A heading at a wide width

This render is 1024 pixels wide. The media query does not match, so the base size stands.

h1 {
  font-size: 32px;
}
@media (max-width: 600px) {
  h1 {
    font-size: 20px;
  }
}

The same styles, narrow

The same code renders again at 500 pixels wide. The query now matches, and the smaller size applies.

h1 {
  font-size: 32px;
}
@media (max-width: 600px) {
  h1 {
    font-size: 20px;
  }
}

A wide-only rule, narrow screen

This rule paints the box only at widths of 700 pixels or more. At 500 pixels the box keeps its default background.

@media (min-width: 700px) {
  .box {
    background-color: lightblue;
  }
}

A wide-only rule, wide screen

The same code renders again at 1024 pixels wide. The condition is met, and the box is painted.

@media (min-width: 700px) {
  .box {
    background-color: lightblue;
  }
}

Example

h1 {
  font-size: 32px;
}
p.intro {
  font-size: 16px;
}
@media (max-width: 600px) {
  h1 {
    font-size: 20px;
  }
  p.intro {
    font-size: 14px;
  }
  .box {
    background-color: lightblue;
  }
}

Key points

  • max-width in a media query means up to that width
  • min-width in a media query means from that width upward
  • A media query tests the viewport, not the device itself
  • Styles outside the query apply at every width
  • Breakpoints are chosen where the design stops working, not per device

In this example, the base rules set a large heading and a standard introduction size. The media query holds the narrow-screen rules. This render is 500 pixels wide, so the query matches. The heading and introduction shrink, and the box gains a pale background.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

When does @media (max-width: 600px) apply its styles?