Skip to content

CSS @custom-media at-rule to manage media queries #714

@ramiy

Description

@ramiy

Description

The Media Queries Level 5 specification introduces the @custom-media at-rule, which acts as an alias for complex and repetitive media queries. Instead of hardcoding media query breakpoints across multiple CSS files, developers can declare breakpoint values using @custom-media rules. These custom media queries can then be reused, streamlining CSS management and improving maintainability.

With @custom-media, developers can centralize all breakpoint definitions in one place, ensuring consistency across stylesheets. When a breakpoint value needs to change, only the @custom-media declaration must be updated, and all instances across CSS files are automatically adjusted.

Use them as aliases in multiple breakpoints:

@custom-media --narrow-window (max-width: 32em);

@media (--narrow-window) {
}

@media (--narrow-window) and (hover) {
}

@media (--narrow-window) and (orientation: portrait) {
}

Use them for grouping all your breakpoints in one place:

@custom-media --mobile-screen (max-width: 480px);
@custom-media --tablet-screen (max-width: 768px);
@custom-media --laptop-screen (max-width: 1024px);
@custom-media --desktop-screen (max-width: 1440px);
@custom-media --widescreen (min-width: 1441px);

I was hoping my MDN PRs will be merged before Interop 2025, but as it was not merged yet, check the following PRs for more information and code examples:

Specification

Browser Bugs

Additional Signals

Real-World Application: Elementor Case Study

I currently work at Elementor, a popular WordPress page builder powering over 25% of all WordPress websites and ~11% of all websites globally.

We continuously strive to optimize our CSS for millions of websites. Currently, when our users update breakpoint sizes, we need to re-generate multiple CSS files.. With @custom-media support across all browsers, we will be able to simplify this by redefining new breakpoint size in a single line of code. This eliminates the need for full CSS regeneration because only the last declared @custom-media rule is applied when multiple rules share the same name.

The Way Forward

Just as Custom CSS Properties revolutionized styling by enabling dynamic values, Custom Media Queries will significantly enhance how developers handle responsive design. By enabling media query reusability and eliminating redundancy, @custom-media is poised to be a game changer in the future of CSS development.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions