CodeBlanks Logo Icon CodeBlanks

Media query basics

CSS course · Intermediate · Lesson 47/98

Learn the @media rule and screen width conditions.

What is an @media block?

An @media block groups styles that apply only when a condition is met. The most common condition is screen width. You can use one set of styles on phones and another on desktops.

@media (max-width: 600px) {
  body {
    background: navy;
    color: white;
  }
}

The keyword is @media, the condition sits in parentheses, and the styles go inside curly braces.

The max-width media feature

max-width is a media feature. It means "at most this width". When you write @media (max-width: 600px), the styles apply whenever the screen is 600px or narrower.

This is common in a desktop-first approach, where styles change as you move from desktop to phone. You start wide and add a new @media for each narrower step.

The min-width media feature

min-width means "at least this width". When you write @media (min-width: 768px), the styles apply whenever the screen is 768px or wider.

This is the backbone of the mobile-first approach. You write base styles for phones, then add a new @media at each widening step. This is the recommended approach today.

Exercise Change the background below 600px

Add an @media (max-width: 600px) block. Inside it, write a body selector with background: navy and color: white declarations.

Show example solution
/* Change the body color at 600px and below */
@media (max-width: 600px) {
  body {
    background: navy;
    color: white;
  }
}

Test yourself

  1. When does @media (max-width: 600px) apply?

    @media (max-width: 600px) {
      body { font-size: 18px; }
    }
    • Only when the screen is wider than 600px
    • Only when the screen is 600px or narrower
    • At every screen width
    • Only in landscape mode
    Show answer

    Only when the screen is 600px or narrower — Correct. The max-width: 600px condition is met when the screen is 600px or narrower.

  2. Complete the @media block

    @media (max-width: ____) {
      body { background: navy; }
    }
    Show answer
    @media (max-width: 600px) {
      body { background: navy; }
    }
  3. Which is true?

    • max-width applies to wide screens, min-width to narrow screens
    • Both apply only when printing
    • Both apply at all times
    • max-width applies to narrow screens, min-width to wide screens
    Show answer

    max-width applies to narrow screens, min-width to wide screens — Correct. max-width means 'at most', min-width means 'at least'; max applies when narrowing, min when widening.

All lessons in Intermediate