Skip to content

[css-values]: Express conditional values in a more terse way  #5009

Open

Description

@jonathantneal

Which active (or yet reviewed) proposals might allow CSS authors to express @media conditional values in a more terse way?

The following hypothetical code was widely shared among Twitter users this last week:

A picture shared on Twitter of code, which is written out after this link

@media (max-width: [1200px, 768px, 425px]) {
  .text-box {
    font-size: [24px, 20px, 16px];
    padding: [50px, 30px, 10px];
    margin: [50px 25px, 25px 12.5px, 12.5px]
  }
}

This particular hypothetical solution is described by the author as a “media query [that] is an array of sizes and your property value arrays are linked to those sizes” *.

Activity

  1. Crissov commented on Apr 27, 2020

    @Crissov
    Contributor

    Looks like something for a preprocessor (SASS/SCSS, LESS).

  2. CyberAP commented on Apr 27, 2020

    @CyberAP

    This would basically reserve square brackets in properties to be used exclusively in conjunction with media queries. It certainly looks like a preprocessor target.

  3. jonathantneal commented on Apr 27, 2020

    @jonathantneal
    ContributorAuthor

    That is well pointed out, @CyberAP. This particular implementation is not feasible in actual CSS. I should have done more to point this out.

    I want to reiterate that I’m looking for thematically similar proposals that would allow CSS authors to express conditional values in a more terse way. The hypothetical solution above and the attention it received effectively demonstrate this desire by authors, I believe.

    Please forgive me if I butcher this next part. An additional request of mine is that we consider not (even passively) encouraging preprocessors to accomplish tasks that create syntactical interop issues with actual CSS. I can understand why it has been suggested; and your freely-given feedback means a great deal to me. My experience has been that popular userland experiments can positively and negatively impact standardization. When we encourage solutions to work alongside the language as much as possible, we drive experimentation that can lead to and help inform future standardization. However, if the interop is missing, sometimes those userland experiments actually get in the way. I believe both results have been the case with Sass and CSS (Sass has since been wonderfully responsive to interop issues). Again, this is something I should have done more to point this out in my original issue, and I hope my request does not discourage anyone.

    EDIT: I changed "_ If that education is not there_" to "However, if the interop is missing", because I think it makes a lot more sense. See, knew I’d goof it. 😬

  4. LeaVerou commented on Apr 28, 2020

    @LeaVerou
    Member

    Why not set a variable in a media query and express the other values as calculations over it? Presumably they're not completely random numbers, but there is some logic to them. Why not make it obvious?

  5. meduzen commented on Apr 28, 2020

    @meduzen
    Contributor

    Why not set a variable in a media query and express the other values as calculations over it? Presumably they're not completely random numbers, but there is some logic to them. Why not make it obvious?

    It’s a good option that will work for some layouts, not for others. There’s not always a possibility to extract a logic across media queries.

  6. tabatkins commented on Apr 28, 2020

    @tabatkins
    Member

    So I'll start by saying I get the urge here - the current MQ situation is definitely a bit annoying. Either you have to duplicate your whole stylesheet into each MQ, meaning that the same rule shows up in different versions spread across the entire sheet (making it hard to ensure you keep everything up-to-date while editting), or you keep rules together but have to duplicate the MQ over and over again.

    This syntax, tho, and likely anything close to it, is unworkable. It depends on the MQ you're differentiating on to be only a single condition's value, and the properties you want to set differently based on MQ to all be exactly the same (or else duplicate the same "initial" value across several of the clauses). And that's not even getting into the actual syntax shenanigans; maybe we could work this with a ; separator, if it was always setting the whole value for the property.

    That said, I think the core problem will get better if we keep pushing on MQ improvements, namely (1) letting you nest MQs into style rules, and (2) letting you set custom MQs or full custom at-rules.

    The example above is a lot better if written as:

    .text-box {
      @media (--size:small) {
        font-size: 24px;
        padding: 50px;
        margin: 50px 25px;
      } @media (--size: medium) {
        font-size: 20px;
        padding: 30px;
        margin: 25px 12.5px;
      } @media (--size: large) {
        font-size: 16px;
        padding: 10px;
        margin: 12.5px;
      }
    }

    Or even, with a custom at-rule that just transforms itself directly into an @media rule:

    .text-box {
      @--small {
        font-size: 24px;
        padding: 50px;
        margin: 50px 25px;
      } @--medium {
        font-size: 20px;
        padding: 30px;
        margin: 25px 12.5px;
      } @--large {
        font-size: 16px;
        padding: 10px;
        margin: 12.5px;
      }
    }

    Or going a step further, with a custom function that evaluates a predefined MQ and selects a value accordingly:

    .text-box {
      font-size: --page-size(24px; 20px; 16px);
      padding: --page-size(50px; 30px; 20px);
      margin: --page-size(50px 25px; 25px 12.5px; 12.5px);
    }

    All of these should be possible in the future; the latter two would require a bit of JS to work, but not a complex amount.

  7. Crissov commented on Apr 28, 2020

    @Crissov
    Contributor

    I was recently thinking whether CSS Values should include a value type for an indexed set, array, tuple, group, enum, whatever with multiple entries of the same basic type. They would need special functions, of course, to access the values or a reduction of them. I think MQ-dependent values like these could make a valid use case for them.

    @media screen and (max-width: 1200px) {
      --index: 3; --screen: wide;
    }
    @media screen and (max-width: 768px) {
      --index: 2; --screen: normal;
    }
    @media screen and (max-width: 425px) {
      --index: 1; --screen: narrow;
    }
    .text-box {
        font-size: calc(4px * (3 + var(--index)) );
        padding: set(var(--index), 10px, 30px, 50px);
        margin: set(var(--screen), var(--margin));
      --margin: (narrow = 12.5px), (normal = 25px 12.5px), (wide = 50px 25px);
    }
  8. carlosame commented on Apr 28, 2020

    @carlosame

    What about defining a switch function:

    switch(<integer [1,∞]>, <toggle-value>#)

    If the first argument is not positive, the value becomes invalid (yes it could start from zero too). The other arguments (I chose the toggle-value from the toggle() function, not sure if there is something more general) are selected according to the first: 1 means the first toggle-value is returned, 2 the second, etc.

    If the first argument evaluates to N and there are M toggle-values, with M<N, then the last toggle-value is used. The toggle-values could also contain var() functions, if the switch is resolved before the vars are substituted/evaluated.

  9. carlosame commented on Apr 29, 2020

    @carlosame

    @Crissov I see that you edited your post to add a block which included this:

    padding: set(var(--index), 10px, 30px, 50px);

    If you have a specific proposal, I'd appreciate a description of it like I did with mine. Editing a previous post to add something that looks very similar to my proposal in the next message... does not help.

  10. tabatkins commented on Apr 29, 2020

    @tabatkins
    Member

    Hmm, a generic value switcher like that might make sense, yeah. Would let us hit the use-case pretty simply, without needing to wait for future Houdini stuff, and with a pretty minor syntax tax overall. Mechanics are no more complex than any other variable-related stuff.

    Like I'd said earlier, pretty sure we'd need to use a ; as the value separator there, but otherwise yeah it's all good. Functionally identical to just setting several variables in the MQ, but letting you avoid naming the temporary values, and keep them clustered at point-of-use rather than spread across MQs.

  11. Crissov commented on Apr 30, 2020

    @Crissov
    Contributor

    @carlosame I was just trying to explain “They would need special functions, of course, to access the values …” with pseudo-code. The “or a reduction of them” part is for instance found in #544, #905, #2826 and #4700.

  12. bkardell commented on May 7, 2020

    @bkardell
    Contributor

    If we are going to talk about a switch like function solution I think this conceptually fits with the existing switch/context proposal in that it seems like the underlying machinery could let you write tab's custom thing with some context property (which of course needs a whole topic discussion, but so does tabs I think) something like

    @media (max-width: [1200px, 768px, 425px]) {
      .text-box {
        font-size: switch(
        	(breakpoint == 1) 24px; 
        	(breakpoint == 2) 20px; 
        	(breakpoint == 3) 16px;
        );
        padding: switch(
        	(breakpoint == 1) 50px; 
        	(breakpoint == 2) 30px; 
        	(breakpoint == 3) 10px;
        );
        margin: switch(
        	(breakpoint == 1) 50px 25px; 
        	(breakpoint == 2) 25px 12.5px; 
        	(breakpoint == 3) 12.5px;
        );
      }
    }
    

    So then this would let us unify underlying work and answer a bunch of questions 'together' rather than entirely disjointly. We could easily sugar this as something like..

    @media (max-width: [1200px, 768px, 425px]) {
      .text-box {
        font-size: breakpoint(
        	24px; 
        	20px; 
        	16px;
        );
        padding: breakpoint(
        	50px; 
        	30px; 
        	10px;
        );
        margin: breakpoint(
        	50px 25px; 
        	25px 12.5px; 
        	12.5px;
        );
      }
    }
    

    But at least a lot of the harder questions can be centralized?

  13. carlosame commented on May 7, 2020

    @carlosame

    The main intent with my switch function is, precisely, to be able to somehow 'centralize' the switch at the place where the author is naturally putting the declarations, as @tabatkins mentions ("clustered at point-of-use"), reducing the verbosity of media rules.

    So in a media rule you set an index-like property (there is also the possibility to mix it with some calc() tricks), and also add all the rules that are really specific for that media query.

    Then, you may want to put the switch at the "main" sheet, and for example if you have three index levels you do not need to always specify three values:

    margin: switch(var(--mq-level); 50px 25px; 25px 12.5px; 12.5px);
    font-size: switch(var(--mq-level); 24px; 20px);
    

    Which also means that if you add another level and forget to update some declaration(s), things keep working.

    Your suggestion (which is somewhat similar to the original proposal in this issue), instead, implicitly builds something similar to a matrix of values, that in principle have to be always fulfilled.

    Finally, my switch allows for invalidating the declaration, which may sometimes be useful.

  14. 61 remaining items

  15. LeaVerou commented on Feb 25, 2021

    @LeaVerou
    Member

    @faceless2 Yeah, it would need to have IACVT behavior just like var(). Are there any use cases where that is a problem?

  16. tabatkins commented on Feb 25, 2021

    @tabatkins
    Member

    Losing the ability to do parse-time fallback, and thus the ability to future-proof your code by providing older, more widely-supported variants, isn't something we should give up lightly. It's been vital to allowing CSS to safely evolve over the years. IACVT behavior was introduced to var() as an unfortunate compromise.

    For @faceless2's example, for instance, they couldn't use src() in the function and provide a fallback url() for older browsers.

    Also note my comment in #5009 (comment); if the output type is var-like than that means Typed OM can't offer any better representation for the output values than CSSUnparsedValue. cond(), on the other hand, can actually provide the output types as a CSSNumericValue, because it knows what type they are.

  17. LeaVerou commented on Feb 25, 2021

    @LeaVerou
    Member

    The ability for parse-time fallback was far more important in the past before @supports.
    Today, given the increasing popularity of custom properties, it's becoming harder and harder to rely on it anyway.
    Note that for @faceless2's example cond() still wouldn't work (if I understand it correctly), since src() and url() are not the kinds of simple math values that this would need to be restricted to.

    Also note my comment in #5009 (comment); if the output type is var-like than that means Typed OM can't offer any better representation for the output values than CSSUnparsedValue. cond(), on the other hand, can actually provide the output types as a CSSNumericValue, because it knows what type they are.

    Why is that? I thought Typed OM returned computed value time representations? If not, there should be something that does.

  18. mirisuzanne commented on Feb 25, 2021

    @mirisuzanne
    Contributor

    I agree with @LeaVerou that var-like behavior is not a problem for authors, even if it was an unfortunate compromise, and that many use-cases (flexbox & grid-templates stand out) rely on any-value output. Parse-time fallback is great, but we also have @supports. I do not believe that authors will spend the time to distinguish between two seemingly-identical functions just to get parse-time fallback in a subset of use-cases. Instead we'd be introducing non-obvious failures, any time an author without full IACVT knowledge (most authors) adds a var() inside an existing cond(), and suddenly breaks the fallback. Using a math function is not a stable promise that you get parse-time fallback. As a teacher, I would always encourage people to use @supports anyway, for either function, just in case.

    I like where Lea is going with the if() proposal, designed to handle a wide range of condition-types and outputs.

  19. tabatkins commented on Feb 25, 2021

    @tabatkins
    Member

    I thought Typed OM returned computed value time representations? If not, there should be something that does.

    When you get a computed value, yes. You get also get specified values from the OM! As well, anything with %s probably isn't resolving at computed-value time; those are used-value time.

    Using a math function is not a stable promise that you get parse-time fallback.

    This argument applies equally well to any syntax - using rgb() is not a stable promise that you get parse-time fallback either, in that case.

    As a teacher, I would always encourage people to use @supports anyway, for either function, just in case.

    This is a pretty reasonable argument, tho.

  20. joeshub commented on Feb 25, 2021

    @joeshub

    +1 for this array syntax. I have really enjoyed using it already in styled system

  21. mirisuzanne commented on Feb 25, 2021

    @mirisuzanne
    Contributor

    This argument applies equally well to any syntax - using rgb() is not a stable promise that you get parse-time fallback either, in that case.

    Exactly. :) My point was that the IACVT ship has sailed at this point, and impacts any CSS that might use variables. No one can rely on any function to consistently have parse-time fallback.

  22. matthew-dean commented on Jun 16, 2021

    @matthew-dean

    An if()-style function is extremely useful in having a declarative way to choose options. It's how Less libraries embed a lot of conditional logic without more verbose mixin or @if at-rule-like constructs.

  23. fantasai commented on Oct 28, 2024

    @fantasai
    Collaborator

    Alright so since this issue was filed we have acquired:

    So far it seems like the other two ideas that are not covered are, these which we've filed separately:

    Did I miss anything? Can we close this issue? If you participated in this discussion let us know what you think! ^_^

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