Skip to content

[selectors][mediaqueries] :media() pseudo-class as a shortcut for one-off media queries #6247

@LeaVerou

Description

@LeaVerou

Authors often need to duplicate rules across media queries and selectors. For example, this kind of thing is common:

@media (prefers-color-scheme: dark) {
	:root {
		/* dark mode rules */
	}
}

:root.dark {
	/* duplicated dark mode rules */
}

To my knowledge, there is no way to reduce this duplication with CSS, even if we take CSS nesting into account. Authors either write flimsy JS to toggle the class per the media query, use preprocessor mixins, or just live with the duplication.

Also, often media queries only contain a single rule, and could benefit from a more concise syntax.

With this proposal, the code above would be written as:

:root:is(.dark, :media(prefers-color-scheme: dark)) {
	/* dark mode rules */
}

Any :media() pseudos within a selector would desugar as media queries, joined with and and prepended with not accordingly (e.g. :media(foo):not(:media(bar)) should desugar to @media (foo) not (bar) {...}).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions