Skip to content

[css-values-5] Maybe min, max and step should not be part of the random-caching-key #11742

Closed

Description

@smfr

Currently, CSS Values 5 says that the min, max and step are part of the random-caching-key.

However, this prevents some possibly useful techniques where an element shares the same random value, but with different min, max and step with another property on the same element, or with another element.

Conceptually, I would expect that the underlying 0-1 random number is sampled based only on the dashed-ident or per-element keyword, and then min, max and step are just math applied to that underlying value.

Consider

        .box {
            background-color: blue;
            height: random(per-element, 50px, 100px);
            width: random(per-element, 100px, 200px);
        }

I want this box to have a random size, but always a 2/1 aspect ratio. With the current spec, width and height get their own random values.

Another example might be that you have two elements that want a width based on a single random value, but they quantize that value in different ways.

Activity

  1. tabatkins commented on Feb 19, 2025

    @tabatkins
    Member

    The issue is that if min/max/step aren't included, then it exposes details of exactly how you generate the random value.

    To avoid that, I'd have to specify that the random value is, specifically, a 0-1 real, and then specify exactly how it's turned into the random value. (aka, scaled to the desired range, or converted to a 0-N integer for the step)

    I definitely could do that, and it would avoid some other oddities (like 1em and 16px potentially being the same caching key). It just might slightly restrict how you can actually generate the random value a bit.

  2. fantasai commented on Feb 19, 2025

    @fantasai
    Collaborator

    I want this box to have a random size, but always a 2/1 aspect ratio. With the current spec, width and height get their own random values.

    I think the more obvious way to do this would be to use the same random() function in both, like this: width: calc(random(per-element, 50px, 100px)*2).

    Another example might be that you have two elements that want a width based on a single random value, but they quantize that value in different ways.

    You can do the same thing for this: pull out the random() function and pipe it into a round() function.

    I think these use cases are relatively rare, and it's more obvious what you're doing if you synchronize the random() functions.


    I think what's more likely, actually, is that you want two random() functions with identical arguments to return different values. For example, maybe you want a bunch of randomly sized boxes on your page with their widths and heights between 10px and 100px:

    width: random(10px, 100px);
    height: random(10px, 100px);
    

    But this will generate squares right now, right? It seems to me that requiring a shared name to tie them together makes more sense than requiring different names to differentiate. As you say, if you accidentally end up with two random() functions with shared used values right now, they'll get accidentally tied together.

    The important thing is to make sure that random()'s internal randomness value is part of its computed value so that it inherits correctly; but having each unnamed instance be unique actually makes more sense to me than making identical arguments return identical values... unless they're explicit about wanting to repeat a value, people usually want more randomness out of their random()s, not less, right?

  3. smfr commented on Feb 19, 2025

    @smfr
    ContributorAuthor

    To avoid that, I'd have to specify that the random value is, specifically, a 0-1 real, and then specify exactly how it's turned into the random value. (aka, scaled to the desired range, or converted to a 0-N integer for the step)

    That's how my brain expected it to work. But maybe that's programmer brain.

  4. smfr commented on Feb 19, 2025

    @smfr
    ContributorAuthor

    See also #11747, which would be resolved in the min/max/step were not part of the random key.

  5. tabatkins commented on Feb 24, 2025

    @tabatkins
    Member

    These arguments are pretty convincing, and being able to knock out #11747 would be nice. However...

    But this will generate squares right now, right? It seems to me that requiring a shared name to tie them together makes more sense than requiring different names to differentiate. As you say, if you accidentally end up with two random() functions with shared used values right now, they'll get accidentally tied together.

    The issue with making a "default" random() (without an explicit caching key) assume a unique key is that it's not very clear to authors when such a key would be generated. For example:

    .rectangle {
      /* these would be different random values */
      width: random(10px, 100px);
      height: random(10px, 100px);
    }
    
    .rectangle-2 {
      /* these would be different random values */
      --size: random(10px, 100px);
      width: var(--size);
      height: var(--size);
    }
    
    @property --size2 { syntax: "<length>"; inherits: true; initial-value: 0px; }
    .square {
      /* these would be the *same* random value, making squares */
      --size2: random(10px, 100px);
      width: var(--size);
      height: var(--size);
    }

    To an extent authors already have this confusion, since --foo: 1em; has different inherited behavior for registered vs unregistered custom props, but this random() behavior would make it visible even before inheritance. (Technically the same behavior distinction also occurs for values like 1em, it just doesn't matter in practical terms whether 1em resolves in the custom prop or in the substituting prop.)

    This is how I arrived at the current caching behavior - it can result in accidentally linked random values sometimes, but it also ensures that authors don't have to care about when the substitution occurs.

    So, hm, tradeoffs either way. Maybe it is better to force authors to think about the variable resolution time in return for having "more random" behavior by default and avoiding the value-resolution dependence.

  6. tabatkins commented on Feb 24, 2025

    @tabatkins
    Member

    Ah, right, the other reason I made the current behavior is it reduces the coupling to the precise source document. That is, currently, you can have multiple rules applying the same declaration to an element, and it's the exact same behavior as only having one of them apply. With "implicit unique key", you lose this: having multiple stylesheets applying the same styles to an element will give different results. This exposes things like stylesheet deduping, which currently are undetectable from inside the page. It also exposes the difference between applying a style to multiple elements via a selector and via style attribute. And the difference between .foo, .bar { width: random(); } and .foo { width: random(); } .bar { width: random(); }. All of these things are indistinguishable today, and I'm betting a lot of tooling implicitly depends on this.

    The current behavior instead makes the caching key based purely on the source text itself, not its location, so you can't tell whether the same value is applied from several rules or just one, or if a repeated stylesheet is duped or deduped, etc.

    The accidental linking of functions that happen to have the same arguments is just an unfortunate side effect. I included as much data as possible in the key precisely to make this less likely to happen by accident.

  7. tabatkins commented on Feb 26, 2025

    @tabatkins
    Member

    So just to distill this down, my pushback here is that, today, for all CSS values, the precise source location of a value doesn't matter. (Some things care about which tree context a value's stylesheet is in, but that's the extent of it.) So .foo, .bar { prop: value; } is exactly identical to .foo { prop: value; } .bar { prop: value; } in terms of observable effects, .foo { prop: value; } is identical to .foo:nth-child(even) { prop: value; } .foo:nth-child(odd) { prop: value; }, etc.

    Having random() infer a caching key from its source location would break these equivalencies. I don't know that ya'll have fully considered this ramification, and how tooling might currently be implicitly depending on it. It also has weird interactions with unregistered variables, since its "source location" would be the real/registered property it's subbed into, instead.

    The only way to avoid this is to make the random() value depend, in some way, only on its arguments. Some possibilities:

    • The current spec takes all arguments into account to decrease the chance of accidental coupling between independent values.

    • We could alternately just make it depend solely on the key argument. This would mean that all values are associated by default.

    • I know I originally considered making the default key dependent on the property it's used in. That might be a good middle ground. Still a little confusing in variables, but it means that the values will be associated when used in the same property and unassociated when used in others, which should usually be right. (Registered custom properties will still resolve the random() "early" so they'll be the same value everywhere.)

  8. fantasai commented on Mar 5, 2025

    @fantasai
    Collaborator

    Definitely random() shouldn't infer a caching key from its source declaration. But I think we can and should give it maximum randomness unless the author explicitly ties things together.

    Randomness needs to resolve at computed-value time. That's required for it to inherit sensibly.

    Given that, I think each random() instance (unless otherwise specified by the author) should compute independently. If you specify the same random() function twice in a single property on a single element, or on two different properties, or on two different elements, they would compute to different values. Essentially, if you don't specify a caching key, we throw in the property name, an index (this is the Nth random() in the[+] value, or maybe just generate a unique identifier), and the element identity as the caching key.

    Then if the author wants to tie things together, they can do that explicitly. Two random() functions compute to the same value if they share an identifier, with per-element essentially subbing in the element's identity. So random(--foo, 1, 10) always computes to the same value across the entire page; and random(per-element, 1, 10) always computes to the same value on a single element, but different values on different elements; and random(per-element --foo, 1, 10) computes differently than random(per-element --bar, 1, 10).

    Yes, that means registered custom properties behave differently because they compute things up front. But that's already true, as you point out.


    The one other thing to be careful of is shorthand properties and omitted values. We probably want margin: random(1, 10) to resolve to the same random value on all four sides simply because if we don't, then splitting a property into longhands later becomes problematic. (Also it's a reasonable expectation for shorthands, to duplicate the value.) We can solve this by saying that random() is keyed before expansion.

  9. Loirooriol commented on Mar 5, 2025

    @Loirooriol
    Contributor

    If you specify the same random() function twice in a single property on a single element

    So I think you are saying the default key should be a tuple of

  10. tabatkins commented on Mar 5, 2025

    @tabatkins
    Member

    Essentially, if you don't specify a caching key, we throw in a unique identifier and the element identity as the caching key.

    This is still hiding the complexity. What, precisely, is the scope of the uniqueness? We need the ID to be stable across styling passes, and across the same style applied by different rules, but we also need it to be different across... some boundary. At minimum, between properties. We probably want multiple uses in the same property to be unrelated, too.

    Ah, now that I'm trying to find some text I remembered seeing, I notice you were more specific in the original version of your comment in my email, but editted it to be more generic later. I think your original suggestion is indeed exactly what we'd have to do: construct a key from the property it's used in (recording the shorthand used, before expansion into longhands) + an index for how many random functions precede it in the value. (+ some extra entropy for the pageload itself, so different pages or different visits to the same page are unrelated, but that's already baked into the definition and applies even when a key is given)

    It would be interesting if we could also bake in some entropy from the token stream itself, so using the same number of random()s on the same property, but changing the rest of the property value in some way, would also result in different values. However, that requires a very precise canonicalization of the value into some sort of bytes, and I don't know that it's worthwhile to do so. It should probably be fine to just stick with property+index; you usually won't notice the connection.

  11. tabatkins commented on Mar 5, 2025

    @tabatkins
    Member

    Note that this does still mean that, if you don't use per-element, every first instance of random() on a particular property across the entire page will share the same random value. That might be a little surprising, but I don't think we can avoid that without violating the equivalencies I mentioned earlier.

    Note this introduces more case where we will need to use internal values, raising the priority of #8055

    ...unless we specify that it's literally equivalent to specifying --margin-1/etc as the key. Then we can just reflect that directly. I don't see any particular reason that would be bad? It seems unlikely to clash with anything an author actually provides, and it lets them manually hook it if they do want to. (That's not necessary since they could just specify the key themselves and then use it elsewhere, but hey.)

  12. tabatkins commented on Mar 6, 2025

    @tabatkins
    Member

    Closely related issue: I'm trying to make sure that custom properties work in an understandable way, both registered and unregistered.

    Unregistered is easy, they're just a little weird. They don't even recognize that a random() function exists, so everything about them waits until they're actually substituted - both computation of the default caching key, and resolving the per-element value. A little tricky, but explainable.

    Registered properties present an issue, however. They'll see the random(), so they can compute the default caching key based on the custom property. And if the computation is fully resolveable by computed-value time, they can even handle per-element based on the element the custom property is applied to. But they're substituted as token streams, still, so if the random() isn't fully resolved by inheritance time (it contains a %, for example), then it'll remain as random() and inherit as such, finally applying per-element on the element it's actually substituted into. That's weird! The behavior of random() shouldn't depend on its numeric arguments at all, and double shouldn't do so specifically only when used in a registered custom property!

    I could hand-wave some hidden state that has to be carried with it, but I'd prefer avoiding that if at all possible. This suggests that the "random base value" that is computed at computed-value time needs to be explicitly exposed, so that the computed value of a random() or random-item() function is some other, non-random function, with the random value subbed in.

    That is, at computed-value time:

    • random(..., A, B) computes to calc(R * (B - A) + A), where R is the 0-1 random value
    • random(..., A, B, by C) computes to calc(R * C + A)`, where R is the random int between 0 and however many C steps fit between A and B. (Or to the same as the previous bullet, if the range is big enough and C is small enough that it hits the "just ignore the step" behavior.)
    • random-item(..., A, B, C) just computes to A, B, or C, as appropriate.

    We then rely on normal computed-value behavior from there, simplifying if possible. This would result in an observable calc() showing up in some cases for the computed value (rather than being either random() or a fully-resolved value, as in the current spec).

  13. tabatkins commented on Mar 6, 2025

    @tabatkins
    Member

    Uggghhhhh, no, my second bullet doesn't work, because the R's range depends on actually evaluating A, B, and C. I need to phrase it in a way that lets me keep them unresolved.

    Unfortunately, even if I'm more explicit about the random int calculation, it doesn't let me switch into the "infinite steps" error case; the calc() would instead hit some infinity degeneracies. Oof, and the first bullet point is bitten by that too - the calc() there also hits some infinite degeneracies and doesn't have the same argument range controls. Argh, I think I need to just let the first argument be a 0-1 number, in which case we just treat that as the random base value rather than computing one based on the caching options.

    That is, random(.5, 100px, 200px) will just resolve to 150px. This syntax wouldn't be designed for authors, and generally wouldn't be seen by authors using random() except in the weird case I outlined above. We can even say it has a special keyword of its own that makes it clear it's not for author use, like random(ua-resolved-value 0.5, 100px, 200px) or something.

  14. tabatkins commented on Mar 6, 2025

    @tabatkins
    Member

    Hm, just spitballing if we could handle this via calc-range() or whatever (the "interpolation" variety).

    It would need the by C ability added to the between-stops interpolation qualities. But that's also a little strange - A+n*C doesn't necessarily hit B; the current random() spec handles this by just suggesting you write your B to slightly overshoot, and lets the actual end of the range be exactly an A+n*C value. We'd need to be able to round the endpoint down a little...

    @function --step-range-limit(--a, --b, --c) {
      --dist: calc(var(--b) - var(--a));
      --step: calc(var(--dist) / var(--c));
      --rounded-dist: round(down, var(--dist), var(--step));
      result: calc(var(--a) + var(--rounded-dist));
    }
    @function --step-count(--a, --b, --c) {
      --dist: calc(var(--b) - var(--a));
      --step: calc(var(--dist) / var(--c));
      result: calc(1 + round(down, var(--dist) / var(--step), 1));
    }
    
    /* then `random(A, B, by C)` computes to... */
    
    calc-range(R,
        0: A,
        by steps(--step-count(A, B, C), jump-none),
        1: --step-range-limit(A, B, C)
    )

    Tho, no, sigh, that still doesn't get me some of the argument handling. I guess I will just need to make random() handle this.

  15. 25 remaining items

  16. mirisuzanne commented on Mar 19, 2025

    @mirisuzanne
    Contributor

    As an author, I prefer more randomness as the default, with options to opt-into shared values - so I really like the change from per-element to match-element (or similar). Most of my use-cases would involve applying randomness to a list of items, and ideally getting different values per item. With the original proposal, I would be opting into the per-element behavior most of the time.

    Without referencing spec lingo, I don't see match-element as a confusing name - I would never think of it as matching the unique element identity – but something like element-shared does seem even more clear.

    I also love @kbabbitt's per-iteration use-case. I would use per-iteration behavior with or without element sharing. I'm not sure I've entirely tracked if either of those is already possible in the proposal.

  17. nt1m commented on Mar 19, 2025

    @nt1m
    Member

    @kbabbitt With the current proposal you should be able to use the custom ident for that:

    @keyframes bounce {
       0% { left: 0px; top: random(match-element --iteration-1, 0px, 1000px); }
      25% { left: random(match-element --iteration-2, 0px, 1000px); top: 1000px; }
      50% { left: 1000px; top: random(match-element --iteration-3, 0px, 1000px); }
      75% { left: random(match-element --iteration-4, 0px, 1000px); top: 0px; }
    }
    
  18. vmpstr commented on Mar 19, 2025

    @vmpstr
    Member

    Sorry if this was discussed already, but I was wondering about a case where one toggles some class with randomness on an element

    .random {
     width: random(100px, 200px);
    }
    ...
    setInterval(() => target.classList.toggle("random"), 1000);
    

    It sounded like this would only pick one random value and then persist that for all other uses of the .random class on that particular element, which doesn't sound too random.

    I wonder if there is an opportunity to include some sort of a generation id in the cache key that updates if the style applicability is interrupted as in the case above. There is somewhat tangential precedent to this in contain-intrinsic-size's last remembered size and how that sticks around while the property is continually applied and is forgotten otherwise

  19. kbabbitt commented on Mar 19, 2025

    @kbabbitt
    Collaborator

    @kbabbitt With the current proposal you should be able to use the custom ident for that:

    @keyframes bounce {
       0% { left: 0px; top: random(match-element --iteration-1, 0px, 1000px); }
      25% { left: random(match-element --iteration-2, 0px, 1000px); top: 1000px; }
      50% { left: 1000px; top: random(match-element --iteration-3, 0px, 1000px); }
      75% { left: random(match-element --iteration-4, 0px, 1000px); top: 0px; }
    }
    

    @nt1m as I understood the proposal, that would select a random value once for each keyframe, and then reuse those same values for every iteration of the animation. Is that not the case?

    The use case I suggested called for a new random value, for every keyframe, for every iteration, but each time a random value is drawn, all elements to which the animation is applied get the same value.

  20. Loirooriol commented on Mar 19, 2025

    @Loirooriol
    Contributor

    we should give oriol a chance to comment on here

    So after a week I'm getting more used to the new proposal. Not opposed, but still a bit concerned it may the a source of confusion if authors assume that random(--foo, 0, 1) will be like list-style-type: --foo or animation-name: --foo where different elements referencing the same ident get the same behavior.

  21. mirisuzanne commented on Mar 20, 2025

    @mirisuzanne
    Contributor

    @Loirooriol I agree that might be something authors assume at first, but I'm not sure that's enough reason to make it the default? If the keyword we land on is clear enough (reading back, I like global) I think it becomes very understandable as a system, even if it's a different system from some custom-idents in CSS.

  22. tabatkins commented on Mar 20, 2025

    @tabatkins
    Member

    Re: per iteration randomness, I agree that using the custom-ident option is the right answer here. If we tried to randomize per keyframe, as in Kevin's example, then it brings in the same issues/confusion that randomizing based on style rule would. Is there a difference between 0% { width: random(...): }, 50% { width: random(...): } and 0%, 50% { width: random(...); }? Both "yes" and "no" are confusing. Relying on authors to solve this themselves with a random ident makes the answer clear.

    That said, if it is something we do end up wanting to support more automatically, I think the right answer is that the auto-generated key would, in addition to the property/index, incorporate the keyframes name and keyframe index. That would mean that each instance of random() in Kevin's example would be distinct by default.


    I was wondering about a case where one toggles some class with randomness on an element [example toggling a class on and off]

    Correct, that would be the same random value every time the class applied.

    I'm pretty opposed to a "generation key" for this, as it would make things distinct in unexpected cases, like .foo { width: random(match-element, 100px, 200px); } when applied to elements that can be streamed in - if two elements appears in distinct styling passes they'd get distinct random values rather than sharing. It would also mean, I expect, that an element would change all its random values if you toggled display:none on and off.

    If you're using scripting and want random values, you can always supply them yourself, at exactly the sharing granularity you desire.

  23. css-meeting-bot commented on Mar 26, 2025

    @css-meeting-bot
    Member

    The CSS Working Group just discussed [css-values-5] Maybe min, max and step should not be part of the random-caching-key, and agreed to the following:

    • RESOLVED: Accept the proposal for changing random caching as stated in the issue.
    • RESOLVED: Go with element-shared for now, keep renaming issue open because many people are unhappy with it
    The full IRC log of that discussion <dholbert> ScribeNick+ dholbert
    <fantasai> scribe+
    <fantasai> TabAtkins: The random() functions currently, by default, are maximally random.
    <fantasai> TabAtkins: two axes controlling how they resolve
    <fantasai> TabAtkins: 1. Which property they're in, and what index in the declaration
    <fantasai> TabAtkins: 2. whether same across all elements or different
    <fantasai> TabAtkins: can change either of these
    <fantasai> TabAtkins: Force same across properties/instances by applying custom ident
    <fantasai> TabAtkins: or force same across elements by using special keyword
    <fantasai> TabAtkins: some opposition from oriol about the way that the element sharing was phrased
    <fantasai> TabAtkins: He preferred previous model where elements shared by default, and opt out
    <fantasai> TabAtkins: Since then several people commented preferring that starting with maximal randomnes is better
    <oriol> q+
    <astearns> ack oriol
    <fantasai> TabAtkins: so my proposal is to adopt the proposed model, and then address naming quesiton
    <fantasai> oriol: My concern is that when you provide the keyword, not clear that you would share across instances but not across elements
    <fantasai> oriol: In our other properties with custom elements, you get same behavior for same custom ident
    <fantasai> oriol: I worry it could create some confusion
    <fantasai> oriol: But I think if you provide random() with no parameter, maximizing randomness is better
    <astearns> ack fantasai
    <TabAtkins> fantasai: one option is that "no parameters" is maximum randomness, using a custom ident gives you global correspondence, and using custom-ident+a keyword gives you shared in an element, but differetn across elements
    <fantasai> TabAtkins: Yes, that would be a "per-element" keyword, discussed already
    <fantasai> TabAtkins: I don't like that because it breaks independence of omitted chunks
    <fantasai> TabAtkins: omitting all params shouldn't be different from the behavior of omitting each individually
    <fantasai> TabAtkins: We usually adhere to that model, so I prefer to stick to that model.
    <fantasai> TabAtkins: Specifying peels back specific aspect of randomness.
    <fantasai> TabAtkins: rather than doing an inversion as soon as you specify anything
    <fantasai> fantasai: I don't mind either way, just saying this is another possible syntax model.
    <fantasai> astearns: so should we resolve on this model of maximal randomness?
    <fantasai> RESOLVED: Accept the proposal for changing random caching as stated in the issue.
    <fantasai> TabAtkins: We need to name the share-randomness-across-elements keyword
    <fantasai> TabAtkins: some options were `element-shared` and `all-elements` ... other suggestions in issue
    <fantasai> Proposal is at https://github.com//issues/11742#issuecomment-2707697957
    <fantasai> [this should go into the resolution]
    <fantasai> astearns: Do we have existing keywords related to this idea?
    <bramus> q+
    <fantasai> Suggested keywords https://github.com//issues/11742#issuecomment-2708387121
    <astearns> ack bramus
    <astearns> ack fantasai
    <bkardell_> +1
    <TabAtkins> fantasai: I think I agree with tim on match-element being confusing, it doesn't really convey... we're not matching this value to this element, liek it does in VT
    <TabAtkins> fantasai: it's "this function should match across all elements", different concept
    <bkardell_> thisfunctionshouldmatchacrossallelements
    <TabAtkins> astearns: should we resolve on 'element-shared'?
    <TabAtkins> fantasai: element-shared sounds weird
    <bkardell_> I think I disagree all elements sounds more obv
    <TabAtkins> straw poll: 1) element-shared, 2) all-elements, 3) both of these suck, i have a better idea
    <TabAtkins> 1
    <schenney> 1
    <ydaniv> just "shared"?
    <astearns> 1
    <bkardell_> 1
    <Kurt> 1
    <fantasai> 2, but I wish I could pick 3
    <miriam> 2
    <alisonmaher> 1
    <bramus> 1
    <ydaniv> 1
    <oriol> Maybe 3) shared-across-elements? Or 2)
    <vmpstr> (abstain)
    <kizu> 2
    <dbaron> 1 (weakly)
    <dbaron> (what about across-elements?)
    <fantasai> +1 dbaron
    <oriol> Not clear if across-elements is varying across elements or caching across elements
    <kbabbitt> match-across-elements ?
    <fantasai> fantasai: match-elements ?
    <fantasai> TabAtkins: too close to v-t-n: match-element
    <fantasai> ydaniv: by-property?
    <dholbert> (I'm not particularly enthusiastic about either of the options but I don't have a better suggestion )
    <emilio> (same as dholbert)
    <fantasai> PROPOSED: Go with element-shared for now, keep renaming issue open because we're all unhappy with it
    <fantasai> RESOLVED: Go with element-shared for now, keep renaming issue open because many people are unhappy with it
  24. romainmenke commented on Mar 30, 2025

    @romainmenke
    Member

    I also find match-element to be very confusing.

    I read it as something that causes the random base value to be specific or matched to one unique element.

    Maybe because match makes me think about identity and element is singular?

    Is it clearer by using a plural? e.g. match-elements

  25. added
    Closed Accepted by CSSWG Resolution
    and removed on Apr 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Closed Accepted by CSSWG Resolutioncss-values-5

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      Sponsor
      SponsoredKunjungi sekarang
      Promo