Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

@media — environment-dependent styles

The @media rule applies nested rules only when a media type and environmental features satisfy its media query.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

@media <media-query-list> {
  <group-rule-body>
}

@media <media-query-list> { <stylesheet> } is a conditional group rule. A query can contain a media type such as screen or print and features such as width, orientation, resolution, pointing capability, or user preferences. A comma separates logical alternatives, and combines conditions, and not negates a query according to the grammar’s scope.

Range syntax permits forms such as (400px <= width < 900px). The min-width and max-width forms are inclusive, so the exact boundary satisfies a correspondingly configured condition. An unknown media feature makes that condition false, allowing an older browser to skip the block without damaging the remaining stylesheet. Results can change as the viewport or system preference changes.

@media does not alter specificity inside the block; when the condition is true, the normal cascade still resolves conflicts. Treat prefers-reduced-motion and prefers-contrast as accessibility signals rather than decorative options. The example sets one threshold to the current viewport width and another one pixel above it, then confirms the inclusive boundary through computed values.

Examples

const width = innerWidth;
const style = document.createElement('style');
style.textContent = `.probe { --at-width: no; --above-width: no; }
@media (min-width: ${width}px) { .probe { --at-width: yes; } }
@media (min-width: ${width + 1}px) { .probe { --above-width: yes; } }`;
document.head.append(style);
const probe = document.createElement('div');
probe.className = 'probe';
document.body.append(probe);
const computed = getComputedStyle(probe);
console.log('width=' + width + '; at=' + computed.getPropertyValue('--at-width').trim() + '; above=' + computed.getPropertyValue('--above-width').trim());

Result

width=1280; at=yes; above=no

The @media rule applies nested rules only when a media type and environmental features satisfy its media query.

Sources