Media queries (@media)

A media query applies a block of CSS only when a condition is true: the window width, the orientation, a dark theme or printing. Responsive design is built on them.

Syntax

@media (min-width: 768px) {
  .cards { flex-direction: row; }
}
@media screen and (max-width: 600px) { … }
@media (width >= 768px) { … }  /* range syntax */
@media (prefers-color-scheme: dark) { … }

Media features and operators

SyntaxWhat it does
min-widththe window is at least this wide — the basis of mobile-first
max-widththe window is at most this wide
(width >= 768px)range syntax from Media Queries 4, works in modern browsers
orientationportrait or landscape
prefers-color-schemedark or light — the theme chosen in the system
prefers-reduced-motionreduce — the user asks for less animation
screen / printthe media type: a screen or a printed page
and"and": all conditions must be true
,a comma means "or": one condition is enough
notnegates the whole query

Example

.cards {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.cards div {
  padding: 12px;
  background: #e0f2fe;
  border: 1px solid #0284c7;
}
@media (min-width: 600px) {
  .cards {
    flex-direction: row;
  }
  .cards div {
    flex: 1;
  }
}
<p>Narrow window: cards in a column. Wider than 600px: in a row.</p>
<div class="cards">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

Result

▶ Open in HTML Editor

Good to know

  • Without <meta name="viewport" content="width=device-width, initial-scale=1"> in the <head>, a mobile browser lays the page out about 980px wide, and media queries for narrow screens don't work as expected.
  • Mobile-first: base styles are for a narrow screen, and @media (min-width: …) adds changes for wider ones. The CSS stays simpler.
  • Ranges must not overlap: (max-width: 767px) and (min-width: 768px), or the range syntax. With equal specificity the later rule wins.
  • A media query looks at the window width, not the parent's; for the size of a container there are container queries (@container).

Sources and specification

See also