Encodera

Thanks for reading!

Donate to the site — we work hard for you.

HTML & CSS reference

@media

Applies rules only under given conditions — the window width, the system theme and others.

Syntax

@media (min-width: 600px) { … }

Parameters

ParameterTypeDescription
min-widthlengthThe rules apply if the window is at least this wide.
max-widthlengthThe rules apply if the window is at most this wide.
prefers-color-schemelight | darkThe theme chosen in the user's system.
prefers-reduced-motionreduceThe user asked to reduce animations.
hoverhover | noneWhether the main input device can hover (a mouse can, a finger cannot).

Examples

One column on a narrow screen, three on a wide one:

<style>
  .cards { display: grid; gap: 8px; }
  .cards div { padding: 12px; background: lightskyblue; }
 
  @media (min-width: 500px) {
    .cards { grid-template-columns: repeat(3, 1fr); }
  }
</style>
 
<div class="cards"><div>1</div><div>2</div><div>3</div></div>

A dark theme by the system setting:

<style>
  .theme { padding: 12px; background: white; color: black; }
 
  @media (prefers-color-scheme: dark) {
    .theme { background: #222; color: white; }
  }
</style>
 
<div class="theme">This block follows the system theme.</div>

Notes

Write the styles for a phone first and extend them for wide screens in min-width media queries — this takes less code. The modern range syntax is also supported: @media (width >= 600px). To adapt a component to its container rather than the window, use @container.

See also

  • @container — Applies rules depending on the size of a container rather than the window.
  • max-width — The maximum width: the element can be narrower, but never wider.
  • grid-template-areas — Draws the grid layout as a map of named areas.
  • @supports — Applies rules only if the browser supports a given property, value or selector.

Related recipes

In the tutorial

  • Media queries — Responsive layout with media queries — the viewport tag, the @media rule, min-width and max-width, the mobile first approach and rebuilding the skeleton.

Thanks for reading!

Donate to the site — we work hard for you.