Media query syntax and range comparisons
Definition and purpose
Media queries conditionally apply rules based on media types or media features. Width queries inspect the viewport, not the width of an individual card.
Inclusive threshold
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a, #b { background: lightblue; } #a { color: navy; } @media (width >= 600px) { #a { color: green; } } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> </div> </body></html>Only the wider viewport receives green.
Syntax and mental model
@media screen and (width >= 600px) combines a media type and a range. and requires both conditions; a comma separates alternatives. (400px <= width < 800px) includes 400 but excludes 800. The older min/max forms are inclusive.
Exclusive upper bound
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a, #b { background: lightblue; } #a { padding: 4px; } @media (300px <= width < 500px) { #a { padding: 12px; } } </style> </head> <body> <div id="p"> <div id="a">A</div> <div id="b">B</div> </div> </body></html>375 falls inside the range; 1280 does not.
Common mistakes
Do not assume a width query identifies touch input. Matching rules still compete in the cascade; a media query does not increase selector specificity.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Fluid and mobile-first layouts. Next lesson: Input capabilities and preferences.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Media query syntax and range comparisons — knowledge check
Five questions on media query syntax and range comparisons.
What does width measure?
What does and mean?
How are alternatives separated?
Does width < 800px include 800px?
Does @media add specificity?