Skip to content

[css-values] Re-adding min() and max()? #544

Closed

Description

@LeaVerou

Perhaps now that Values 3 has gone to CR it's time to reconsider adding min() and max() back into Values 4?

Authors are doing extremely weird hacks with calc() to emulate them in font-size and line-height, which they call "CSS locks". If you google CSS locks you will see how widespread these hacks are becoming, indicating a clear author need.

Furthermore, as CSS variables become more widely used, the need for min() and max() will become even greater. I recall some of the issues that made us drop them 6 years ago can now be solved with the invalid at computed value time concept that Variables introduced.

Activity

  1. Crissov commented on Oct 4, 2016

    @Crissov
    Contributor

    So, for “locks”,

    selector {
      property: /* $min_value ≤ */ $fallback_value /* ≤ $max_value = $min_value + $max_increment */;
    }
    @media (min-width: $min_vw) and (max-width: $max_vw) {
      selector {
        property: calc( $min_value + $max_increment *   (100vw - $min_vw) 
                    //*                               ———————————————————  */
                                                      ($max_vw - $min_vw)  );
      }
    }
    @media (max-width: $min_vw) {
      selector {
        property: calc( $min_value + 0 );
      }
    }
    @media (min-width: $max_vw) {
      selector {
        property: calc( $min_value + $max_increment /* = $max_value */ );
      }
    }

    would become

    selector {
      property: /* $min_value ≤ */ $fallback_value /* ≤ $max_value = $min_value + $max_increment */;
      property: calc( $min_value + $max_increment * min(  (100vw - $min_vw) 
                  //*                                   ———————————————————     */
                                                        ($max_vw - $min_vw), 1) );
    }

    right?

    I wonder if authors would also find good use for mid()dle/avg(), med()ian, mod()e etc.

  2. MadeByMike commented on Oct 10, 2016

    @MadeByMike

    I proposed a map() function that allows for min and max sizes as well as easing and interpolation of more than just length units: #581

    I think this would be a much more versatile approach, especially with things like variable type, where min() and max() might not work.

  3. MadeByMike commented on Oct 10, 2016

    @MadeByMike

    People have shared with me examples of how min() and max() functions in CSS might work in addition to a map() function. So to clarify, I don't think it needs to be one or the other.

    Since calc() allows some min and max functionality (although not with whole numbers) It might be useful to consider other implementations of min and max including returning the min and max value of a set e.g. max(14px, 1em, 1rem, 3vw).

  4. LeaVerou commented on Oct 11, 2016

    @LeaVerou
    MemberAuthor

    It's generally good API design practice to have shortcuts for commonly needed things, otherwise you end up with clunky, verbose APIs that are a pain to use for anything. I will not discuss whether what you're proposing is a good idea or not here, partly because I haven't thought about it much. However, even if it is, using map() to specify the min of two values results in extremely weird and convoluted code. Power is good, as long as it stays out of your way when you don't need it.

  5. Crissov commented on Dec 21, 2016

    @Crissov
    Contributor

    I wonder whether min() and max() would be the best notation, however, especially if these operations were only available within calc(). I know it’s unusual and incompatible with programming languages (which need logic operators and, unlike CSS, have a boolean data type), but maybe < and > (or << and >>) could be used as operators instead.

    {
    min(100px 10em 10vw)      calc(min(100px 10em 10vw));
    min(100px, 10em, 10vw)    calc(min(100px, 10em, 10vw));
    100px < 10em < 10vw       calc(100px < 10em < 10vw);
    100px << 10em << 10vw     calc(100px << 10em << 10vw);
    
    max(100px 10em 10vw)      calc(max(100px 10em 10vw));
    max(100px, 10em, 10vw)    calc(max(100px, 10em, 10vw));
    100px > 10em > 10vw       calc(100px > 10em > 10vw);
    100px >> 10em >> 10vw     calc(100px >> 10em >> 10vw);
    }

    This works well for minimum and maximum where you can compare one pair after the other – CSS has only + not sum() despite grammar issues with the former. It would be more complicated to spec for other statistical functions but straightforward for some other operations, also the character repertoire (i.e. Latin 0 punctuation marks) is limited:

    {
    calc(a | b);	/* median */
    calc(a = b);	/* arithmetic mean, average */
    calc(a # b);	/* either count or mode (work) or geometric mean (doesn’t work) */
    calc(a ~ b);	/* round $a to an integer multiple of $b */
    calc(a _ b);	/* floor, round down $a to an integer multiple of $b */
    calc(a ` b);	/* ceiling, round up $a to an integer multiple of $b */
    calc(a ^ b);	/* $a to the power of $b */
    calc(a % b);	/* $a modulo $b, or $a integer-divided by $b, or remainder of $a/$b */
    calc(a : b);	/* one of the other from the line above */
    /* … */
    }
  6. LeaVerou commented on Dec 21, 2016

    @LeaVerou
    MemberAuthor

    I believe we can't add angle brackets for some syntax reason, which is why we used min- and max- in media queries. But even if we could, your proposed syntax does not look more clear to me at all, and I don't understand why it would only be usable within calc(), there's no reason to not allow it bare. Furthermore, I don't think the other operators are more clear either, both to non-programmers and programmers alike, for different reasons. We don't need more ASCII art in CSS. And the modulo operator being % is a huge mistake IMO, since % has a clearly defined role in language, which is completely different than modulo.

  7. cvrebert commented on Dec 21, 2016

    @cvrebert
    Member

    I believe we can't add angle brackets for some syntax reason, which is why we used min- and max- in media queries.

    Erm, MQ4 uses angle brackets: https://drafts.csswg.org/mediaqueries-4/#mq-range-context

  8. Crissov commented on Dec 22, 2016

    @Crissov
    Contributor

    The reason for avoidance of < (in the past) was compatibility, not really syntax, as far as I remember. I don’t fancy % as a binary operator either, but it has precedent elsewhere.

    The advantages of > over max() are really the same as for + vs. sum(), except that plus is much better established elsewhere. Semantically, > continues with the larger of the adjacent terms, whereas max() selects the largest out of a list. I prefer the latter in programming languages and spreadsheet applications, but, unlike those, CSS has only scalars to deal with – no vectors, ranges, arrays or objects (except perhaps for <<color>> eventually). We don’t need more JS notation in CSS.

  9. frivoal commented on Dec 22, 2016

    @frivoal
    Collaborator

    a > b does not read like the larger of a and b to me, but true if a is larger than b, false otherwise. Not just because that's what it means in many programing languages, but because that's what it means in math. I'm not favorable to this notation at all.

  10. Crissov commented on Dec 23, 2016

    @Crissov
    Contributor

    In mathematics, though, < and > are usually only used as relation symbols and not as operators. Outside MQ, CSS does not use logic expressions, unlike pretty much every programming language.

    Pairing the angle brackets, i.e. >min< and <max>, also kinda works for me.

    {
        max(a b c)    calc(max(a b c))
        <a b c>       calc(<a b c>)
        a > b > c     calc(a > b > c)
    
        min(a b c)    calc(min(a b c))
        >a b c<       calc(>a b c<)
        a < b < c     calc(a < b < c)
    
        abs(a)        calc(abs(a))
        |a|           calc(|a|)
    
        round(a, b)   calc(round(a, b))
        [a]b          calc([a]b)
        [a]~b         calc([a]~b)
        a ~ b         calc(a ~ b)
    
        floor(a)      calc(floor(a))          ⌊a⌋
        [a]_          calc([a]_)
        _a_           calc(_a_)
        (a _)         calc(a _)
    
        ceil(a)       calc(ceil(a))           ⌈a⌉
        [a]`          calc([a]`)
        [a]^          calc([a]^)
        `a`           calc(`a`)
        ^a^           calc(^a^)
        (a `)         calc(a `)
    }
  11. MatsPalmgren commented on Dec 23, 2016

    @MatsPalmgren

    Please use function syntax. Readability is much more important than saving a few key strokes.

  12. Crissov commented on Dec 23, 2016

    @Crissov
    Contributor

    Readability is my primary goal, too! It’s so easy to get lost in the parentheses of nested functions.

  13. frivoal commented on Dec 23, 2016

    @frivoal
    Collaborator

    To pretty much everybody who has ever seen that symbol, a > b means "a is larger than b" not "the larger of a and b", so I strongly object to giving it that meaning.

    My objection against <a b> and >a b< is less strong, as there is no existing universally accepted meaning to it. I still don't like them though. max(a b) is much more guessable, much more googlable, easier to search in a a file that mixes markup and css...

  14. Crissov commented on Dec 23, 2016

    @Crissov
    Contributor

    It's a bit like default/fallback values in Lua etc.: Takes some time to get used to, but makes sense.

    Anyway, I'm not feeling strongly about this, just wanted to provide some thinking outside the box.

  15. 15 remaining items

  16. tabatkins commented on Aug 14, 2017

    @tabatkins
    Member

    out-of-order clamping (that is, interpret the smaller one as min and larger one as max, regardless of how they were specified) can definitely be done, but it doesn't match current CSS behavior of min/max pairs. Like "max wins", it can be done manually (where you see the minvalue in the normal expression, instead use min(minvalue, maxvalue), and same with maxvalue and max()), and might be worthwhile to expose with flags.

    (Alternately, just waiting for custom functions could let us handle this. Since this can be done as a simple rewrite of the expressions, it might look something like:

    @custom-function 
      --clamp-close($val, $min-val, $max-val)
      clamp($val, min($min-val, $max-val), max($min-val, $max-val);
    

    )

    Angle clamping can potentially be given special behavior, but can you elaborate on what your preferred behavior is? I can't understand it from your brief description.

    Color clamping is a whole other kettle of fish, with lots of different behaviors one might want to use.

  17. gabriel-peracio commented on Aug 15, 2017

    @gabriel-peracio

    If you give two random angles, there are two possible arcs described. Unless the angles are diametrically opposite (in which case I guess the function would simply return val without clamping), there should be a big arc, and a small arc.

    For instance, if you pass 0° and 90°, there are two arcs: one is 90° and the other 270°.

    Thus, when clamping an angle, say you just passed as parameters 0° for the start, 90° for the end and 110° for the val. Surely you want the function to return 90°, even though 110° is within the greater arc.

    This seems intuitive, and behaves just like the previous example, until you look at things like passing 270° and 0°. You still want to clamp to the the smaller arc of 90°, not the greater arc of 270°. Therefore, passing 110° as val would return 0°, since that is what is closest to being within the arc bounds (you only have to turn 110° to get to 0° as opposed to the 160° you'd need to get to 270°).

    Things also get confusing when you start providing things like 3600° (or any value bigger than 360°, really), but the trivial solution is to just mod it to 360° which would make 3600° equal to 0°. Negative angles also get trivially converted to their positive counterparts.

    Alternatively there could be an angleclamp() function so that people aren't confused by special behavior (for instance start: 2700°, end: 3600°, val: 10° returns 0° instead of 2700° which might be what they are expecting with clamp). A variant that clamps to the greater arc is possibly desirable as well but I haven't found a usecase for it.

  18. gabriel-peracio commented on Aug 15, 2017

    @gabriel-peracio

    As for color clamping, I guess one could just use RGB() and clamp inside the parameters for maximum control

  19. tabatkins commented on Aug 15, 2017

    @tabatkins
    Member

    For instance, if you pass 0° and 90°, there are two arcs: one is 90° and the other 270°.

    That's if you treat the angles as just points on a circle, where spinning 360deg gives you the exact same point. We don't do that in CSS - angles are numbers like anything else; 0deg and 360deg might map to the same direction in the end, but they're treated as completely distinct values otherwise. (So you can, for example, animate from rotate: 0deg; to rotate: 360deg; to make something do a complete spin.)

    So in CSS, if you give 0deg and 90deg, there's only one "arc", going from 0 and 90. Between 0deg and 270deg there's only one "arc", going from 0 to 270. If you want the "small" arc in that second case, use the angles property: specify -90deg and 0deg, or 270deg and 360deg.

    This does suggest that there might be justification for modding angles, for when 0deg and 360deg really are exactly the same for a given application. But it shouldn't be built into clamp().

  20. zcorpan commented on Sep 4, 2017

    @zcorpan
    Contributor

    Should this be closed, given 371d0a1 ? @tabatkins

  21. tabatkins commented on Sep 5, 2017

    @tabatkins
    Member

    Still needs a testcase.

    Also I'd like to split out the clamp() proposal to a separate thread.

  22. dennisgaebel commented on Oct 12, 2017

    @dennisgaebel

    @tabatkins Is there a thread for the clamp() proposal as of today?

  23. tomasdev commented on Jan 23, 2018

    @tomasdev

    just gonna throw this here:

    font-size: min(20vw, 10vh)

  24. ewilligers commented on Jan 28, 2018

    @ewilligers
    Contributor

    There are implementation implications. Currently, implementations can internally reduce any calc to an array of coefficients. (Element dimensions, font size, device orientation might change during an animation, so a calc can't simply be represented as a number of pixels.)

    This proposal requires a slow path of general expression evaluation during each frame's style calculation.

    Suppose we have animation between min(10%, 20vw) and max(30em, 40vh).

    At 75% progress, the result is
    calc(0.75 * min(10%, 20vw) + 0.25 * max(30em, 40vh))

  25. LeaVerou commented on Feb 27, 2018

    @LeaVerou
    MemberAuthor

    @ewilligers Can’t this still be reduced to an array of coefficients, i.e. calc(0.75 * (a * 10% + (1-a) * 20vw) + 0.25 *(b * 30em + (1-b) * 40vh) where a, b ∈ [0, 1] ?

    If a,b change during the animation, you can pre-calculate that.

  26. tabatkins commented on Feb 28, 2018

    @tabatkins
    Member

    That's a nested structure, which can be arbitrarily nested, not a flat array. (Aka a sum of simple values.)

    But we already need to support this sort of arbitrary structure for the unit algebra that the WG resolved on and which is already specced in Typed OM.

  27. felds commented on Mar 6, 2018

    @felds

    @tomasdev I don't get it…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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