w3c / csswg-drafts

CSS Working Group Editor Drafts
https://drafts.csswg.org/
Other
4.5k stars 668 forks source link

[mediaqueries-5] [css-env] Replace `@custom-media` with custom environment variables? #6698

Open valtlai opened 3 years ago

valtlai commented 3 years ago

An issue in the css-env spec says:

ISSUE 3. Define the full set of places env() can be used.

  • Should be able to replace any subset of MQ syntax, for example.

This made me think if we could define custom environment variables and use them in @media queries, would there still be a need for @custom-media or would it become redundant.

That could look something like the following:

@env --narrow-window: (max-width: 30em);

@media env(--narrow-window) {
  /* ... */
}

(The syntax could be different, of course, as the syntax for custom environment variables hasn’t yet been decided.)

luis-pato commented 3 years ago

I think having a way to use env() variables on media queries would be great

MajPay commented 3 years ago

How about passing env variables from the implementation and using it with a provided fallback value?

This could be used fort both - scripts and stylesheets alike.

<link rel="stylesheet" href="style.ss" env-rem-size="18px" />

<style type="text/css" env-breakpoint-large="1024px">
    @media (min-width: env(--breakpoint-large, 800px)) {
        .element {
            background: red;
        }
    }
</style>

<script>
document.querySelector('style').env.breakpointLarge = "1280px";
// removes all styles and re-adds with new env value
</script>

<!-- or even -->
<script env-namespace="my" id="script">
    customElements.define(`${env.namespace || 'vendor'}-hello`, class extends HTMLElement {
        constructor() {
            super();
            this.attachShadow({mode: "open"}).innerHTML = `Hello, <slot></slot>!`;
        }
    });
</script>

<my-hello>John Doe</my-hello>

<script>
document.querySelector('#script').env.namespace = "your";
// triggers error because script has already been evaluated
const script = document.createElement("script");
script.env.foo = "bar";
script.innerText = `console.log(env.foo);`;
document.querySelector('#script').insertAdjacentElement('beforebegin', script);
// console tells "bar"
script.env.foo = "baz";
// triggers error
</script>

I would still support the idea of declaring env-variables inside the stylesheets head (to avoid repeating the same fallback-values over and over again), but the argument-value should take precedence.

If consistancy with svg parameters is important, passing env variables via a url could work as well but i dont like the idea of passing args via a url and making it seem like there is some http pipeline involved.