Skip to content
BENIBIX Learn

Media Query

Development🌐 Web DevelopmentBrowser Code

Also known as CSS Media Query, @media, Media Queries

A CSS rule that only works when a test is true, like a wide screen.

Think of it like

Think of it like a coat rule. If it is cold out, wear the big coat. If not, a jacket will do.

Example

Emma's shop shows one column of products on a phone. At 768 pixels wide and up, a media query makes it three.

Why it matters

One page has to work on a phone and a big screen. Media queries are how a page changes shape to fit.

Definition

A media query is a CSS rule that only applies when a test is true. The most common test is the width of the screen. You write the styles for a phone first. Then a media query adds changes for wider screens, like more columns. It can also test for dark mode, printing or a reader who wants less motion.

Example code

css
@media (min-width: 768px) {
  .products { grid-template-columns: repeat(3, 1fr); }
}
From 768 pixels wide and up, the products sit in three columns.
The same three boxes, stacked on a phone and side by side on a wide screen.

Common mistake

Picking sizes to match one phone model. Pick the width where your own layout starts to look wrong.

Key takeaways

  1. 1
    Only when true. The styles wait for the test to pass.
  2. 2
    Width is the usual test. Change the layout as the screen grows.
  3. 3
    Other tests too. Dark mode, print and less motion.

Compare

Learn it properly