Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to use media queries

Short answer

The rules inside @media apply only while the condition holds. Change the window width:

<style>
  .box { padding: 16px; background: lightcoral; color: white; }
  .box::after { content: "Narrow screen"; }
  @media (min-width: 500px) {
    .box { background: seagreen; }
    .box::after { content: "Wide screen"; }
  }
</style>
 
<div class="box"></div>

Mobile first

Write the base styles for a narrow screen and add min-width for wider ones. The phone gets fewer extra rules, and each breakpoint only adds to the previous one:

.grid { display: grid; gap: 16px; }
@media (min-width: 600px) { .grid { grid-template-columns: 1fr 1fr; } }
@media (min-width: 900px) { .grid { grid-template-columns: 1fr 1fr 1fr; } }

Ranges

The modern range syntax is shorter and clearer than a min-width and max-width pair:

@media (400px <= width < 800px) { .sidebar { display: none; } }

Pick breakpoints by content, not by phone models: where the layout starts to look bad.

Common mistake

Media queries "do not fire" on a phone when the page has no viewport meta tag: the browser assumes a width of about 980px and applies desktop styles. Another trap is order: a media query placed above a normal rule with the same selector loses to it, because the later rule wins.

Functions used in this recipe

  • @media — Applies rules only under given conditions — the window width, the system theme and others.
  • display — Decides how an element behaves in the flow and how it lays out its content.
  • grid-template-columns — The number and widths of the columns of a grid.

Thanks for reading!

Donate to the site — we work hard for you.