CSS Β· Module 21 Β· Lesson 33 of 48

Media Queries & Syntax

What is a Media Query?

Imagine you are printing a magazine. You lay out the text in three columns because a magazine page is wide. Now imagine printing the same article on a tiny bookmarkβ€”you must rearrange the text into a single narrow column so it fits.

In CSS, Media Queries apply different styles to your webpage based on the device's characteristics, most commonly its viewport width:

  • @media (max-width: 600px): Applies styles only to screens that are 600px wide or narrower (e.g., mobile phones).
  • @media (min-width: 768px): Applies styles only to screens that are 768px wide or wider (e.g., tablets and desktop monitors).
  • Why does it matter?

    Without media queries, websites designed for desktops would look tiny and unreadable on mobile phones, forcing users to pinch and zoom to read text. Media queries are the core building block of responsive web design.

    Syntax Breakdown

    Wrap your CSS selectors inside a media block:
    @media (max-width: 600px) {
      body {
        background-color: lightblue;
      }
    }
    
    In this example, the body background color will turn light blue *only* if the screen width is 600px or less.

    Common Mistakes

  • Forgetting curly braces: A media query needs its own set of outer curly braces wrapped around all the CSS rules it contains. Forgetting to close the query's outer brace is a very common syntax error!
  • Missing viewport meta tag: If you forget to place <meta name="viewport" content="width=device-width, initial-scale=1.0"> inside your HTML <head>, mobile browsers will simulate desktop screens, rendering your media queries completely useless!
  • Quick Reference

  • @media (...) β€” Begins a responsive styling block.
  • max-width β€” Targets screens smaller than or equal to the specified size.
  • min-width β€” Targets screens larger than or equal to the specified size.
  • Your Task
    Write a media query targeting screen widths of `max-width: 480px` and set the `body` background color inside it to `yellow`.
    index.html
    Type code above to start the lesson.
    Live Preview