css-mediaquery
Parse CSS media queries and match them against a context — a headless
matchMedia for servers and tooling. A faithful Rust port of the
css-mediaquery npm package
(used by react-responsive, styled-components SSR, and friends). Zero dependencies.
use ;
let ctx = new.media_type.width;
assert!;
assert!;
// units convert just like css-mediaquery: 30em = 480px, 2dppx = 192dpi
assert!;
assert!;
You can also inspect the parsed AST:
let q = parse;
assert_eq!;
assert_eq!;
Why css-mediaquery?
Server-side rendering, static analysis, and headless tooling all need to evaluate
@media queries without a browser. Rust had full CSS parsers but no small,
focused "does this query match this context?" — so this ports the canonical JS one,
verified against it across thousands of realistic (query, context) pairs.
[]
= "0.1"
API
| Item | Purpose |
|---|---|
parse(query) |
Parse into Vec<Query> (one per comma) |
matches(query, &context) |
Whether the query matches the context |
Query::matches(&context) |
Match a single parsed query |
Context::new()… |
Builder: media_type, width, height, resolution, orientation, aspect_ratio, color, … |
Behavior
This mirrors css-mediaquery's semantics, including its quirks:
- Lengths convert to px (
em=rem=16px,in=96px,cm=96/2.54px, …); resolutions to dpi (dppx=×96,dpcm=/2.54); ratios to decimals. - A feature matches only when the context supplies a non-zero value for it. Orientation and aspect-ratio are not derived from width/height — set them explicitly.
- The media type is matched, and
notquits early when the type matches (sonot all and (…)is always false), mirroring the reference implementation. ,is OR; within a query, all expressions must hold (AND).
On well-formed queries it agrees with css-mediaquery exactly. It intentionally
differs only on input that never appears in real stylesheets: numeric values use
Rust parsing rather than JavaScript's Number/parseInt coercions (no Infinity,
hexadecimal, or integers beyond i64), and malformed parentheses degrade gracefully
instead of throwing.
Contributors ✨
This project follows the all-contributors specification. Contributions of any kind are welcome — code, docs, bug reports, ideas, reviews! See the emoji key for how each contribution is recognized, and open a PR or issue to get involved.
Thanks goes to these wonderful people:
License
Licensed under either of Apache-2.0 or MIT at your option.