Skip to content

[css-variables?] Higher level custom properties that control multiple declarations #5624

Open

Description

@LeaVerou

Currently, custom properties can be used to hold small pieces of data to be used as parts of larger values. Despite being called custom properties, they are mainly used as variables. High-level custom properties that control a number of other CSS properties cannot be implemented.

Besides limiting regular CSS authors, this makes it impossible for custom element authors to follow the TAG guideline to avoid presentational attributes and to use a custom property instead, except for very simple bits of data like fonts, colors, and lengths. For anything more complex, web component authors use attributes instead.

Examples from a variety of custom element libraries:

I can collect more if needed, examples abound in nearly all component libraries. Currently, these are impossible to implement as CSS custom properties, for a number of reasons:

  • Each attribute controls multiple declarations, in different ways than just simple value substitution
  • The actual value of the attribute may not be used used anywhere directly.
  • Even in cases where the attribute controls one value only, it is more high level than the corresponding declarations (e.g. pill=on vs border-radius: 999px).

Essentially, component authors need more high-level custom properties that encapsulate the corresponding declarations better instead of just containing fragments of values.

Some proposals to address this problem focus on a JS-based way to monitor property changes [WICG/webcomponents#856], but that appears to be hard to implement. So, I'm wondering if we can address this from CSS instead, especially since it would also address a number of other use cases too that are unrelated to components, a big one being mixins, without the problems that we had with @apply.

There are discussions in the group about inline conditionals [#4731, #5009]. If we were to have such conditionals, these would be possible to implement, but very painful (each declaration value would need to be one or more if()). I was wondering if we could simplify this.

A pseudo-class such as :if-var(<dashed-ident> <comparison-operator> <value>) would solve this ideally, but would likely not be implementable due to cycles. OTOH we already do cycle detection for variables, so perhaps it is? If so, I can flesh out a proposal.

Otherwise, perhaps a nested @rule?

my-input {
	@if-var(--pill = on) {
		border-radius: 999px;
	}
}

With nesting, that would even allow multiple rules, so it would cater for use cases such as e.g. the tabs placement without too much repetition.

One way to implement this would be as sugar for multiple if()s, but that would have the undesirable side effect of all containing declarations being set to initial when the conditional doesn't match and there's no @else, which is suboptimal.

Whatever solution we come up with, some things to consider:

  • The applied declarations may span multiple rules
  • The actual value of the property may only be used indirectly, in conditionals (e.g. --size: [small | medium | large]) or it may be used directly in some values, and also in conditionals.

Current status (updated April 5th, 2021)

This is a long discussion, this is the current status:

  • The initial idea of desugaring to inline if() has several drawbacks and would end up being very confusing for authors.
  • Another idea is to introduce a new type of custom property (custom constant?) that is limited to keywords and numbers, and can be used in a :const() selector. This requires two cascade passes. Constants cannot be set based on :const() selectors.
  • Another idea, proposed by an actual implementer is to use regular custom properties, and have a pseudo that is invalid on the subject compound. This so far seems to address the most use cases.

Activity

  1. jonathantneal commented on Oct 27, 2020

    @jonathantneal
    Contributor

    I love the idea here because the conditions may be created and referenced from within CSS.

    This shares some thematic similarity with the custom :state() pseudo-class. They both help authors style by custom conditions, and both without being directly reflected in serialized HTML. While :state() differs in by using selectors and not supporting assignment within CSS, I’m sharing it so we can glean from their similarities and from feedback on :state(), as that one is already shipping behind a flag in Chrome at the time of this writing.

  2. Que-tin commented on Nov 3, 2020

    @Que-tin

    I think we have to be careful with the naming of the expression, independent of how it's actually implemented. I like the approach of the @if-var but I really don't like the naming, as we don't know if we may expect constants or anything other than variables in CSS in the near or distant future.

    Thinking about it I'd like to have a universally @if that could be used with all types of values not only with custom properties. That way we could use it with other already existing stuff like env().

    e.g.

    .my-input {
    	@if(var(--pill) = on) {
    		border-radius: 999px;
    	}
    }
    
    .my-input {
    	@if(env(safe-area-inset-left) = 20) {
    		border-radius: 10px;
    	}
    }
    

    Thought even further it would be possible to redefine already existing properties. Like background kinda did for background-color. Imagine exposing the screen width or anything to the user agent with like env(width).

    That way it would be possible to combine conditions of each kind and even write media queries and media conditions as part of @if conditions.

    e.g.

    .my-input {
    	@if(env(width) > 768) {
    		border-radius: 10px;
    	}
    }
    
    .my-input {
    	@if(env(width) > 768) and (var(--pill) = on) {
    		border-radius: 999px;
    	}
    }
    
  3. LeaVerou commented on Nov 3, 2020

    @LeaVerou
    MemberAuthor

    @Que-tin Naming is typically decided at the end, all features are proposed with an implied "name to be bikeshedded".

    The problem with such a generic conditional is — as usual — cycles.

    Consider this:

    .my-input {
    	@if (env(width) > 768px) {
    		width: 700px;
    	}
    }
    

    Also, with such generic expressions, there are ambiguities. E.g. what does @if (calc(env(width) + env(height)) > 100%) mean, since percentages mean different things in each property?

  4. LeaVerou commented on Nov 3, 2020

    @LeaVerou
    MemberAuthor

    A pseudo-class such as :if-var(<dashed-ident> <comparison-operator> <value>) would solve this ideally, but would likely not be implementable due to cycles. OTOH we already do cycle detection for variables, so perhaps it is? If so, I can flesh out a proposal.

    It would be good to hear from implementors about this, and in general solicit feedback about a possible way forwards that is implementable and covers most use cases, so I'm gonna go ahead and Agenda+ this.

    Note to chairs: I cannot attend the APAC call, so this would need to be next week.

  5. Que-tin commented on Nov 3, 2020

    @Que-tin

    Good point. There are actually a few exceptions to make at this point, hence percentages as well as integers, should have no meaning at all in this case (seen relative to the element the condition is used in). It would be hard to consider when values are relative and when absolute to the element they are used in inside of the if condition.

    The advantages in my example above would actually be that you could use media conditions (if implemented as e.g. env(width) in the user agent) as part of the CSS properties as already know in e.g. SASS.
    It would also be possible to use things like attr() in the future.

  6. andruud commented on Dec 1, 2020

    @andruud
    Member
    my-input {
            border-radius: 0px;
    	@if-var(--pill = on) {
    		border-radius: 999px;
    	}
    }
    
    #my-input {
           --pill: off;
    }
    

    @LeaVerou Just to make sure I understand the proposal, for <my-input id=my-input> you'd expect a border-radius of 0px, right?

  7. andruud commented on Dec 1, 2020

    @andruud
    Member

    (... interpreting that upvote as a "yes"):

    Having selector matching (@if-var is not very different from a nested :if-var) depend on computed-value-time things adds far too much complexity, even if it's not impossible.

    IMO if we want to if-else on custom properties, then that evaluation needs to happen computed value time, i.e. if-else needs to be part of the value. Or we need something which translates into effectively doing that internally. Or, we add a new kind of custom property which can be known selector matching time.

  8. emilio commented on Dec 1, 2020

    @emilio
    Collaborator

    I agree with @andruud fwiw. I don't understand why something like this:

    There are discussions in the group about inline conditionals [#4731, #5009]. If we were to have such conditionals, these would be possible to implement, but very painful (each declaration value would need to be one or more if()). I was wondering if we could simplify this.

    Is really more painful / complex than what's being proposed here.

    Basically, something like border-radius: if(var(--pill), 0px, 999px); seems simpler and much less action-at-a-distance to me.

    In fact if you make --pill a boolean variable with values 0 or 1, you can already accomplish this particular usecase (border-radius: calc(var(--pill) * 999px)), though I understand there are more complex use cases that aren't probably covered by such a thing (and also it is a bit more obscure than some more explicit syntax).

  9. LeaVerou commented on Dec 2, 2020

    @LeaVerou
    MemberAuthor

    @emilio --pill might not be a good example, as it only needs to control one property, so indeed one if() serves that case just fine. However many of them need to control multiple, often across several rules. I listed a lot more in my original post. Also, once you have several of these custom properties controlling intersecting sets of properties, solving it with if() suffers from combinatorial explosion. Lastly, with if(), you need to provide an alternative (either explicitly or implicitly), whereas a lot of these are about additional "traits" that only set certain declarations when they are actually specified.

    Idea: Would it be easier to implement if one was only able to set other custom properties in these conditionals?

  10. css-meeting-bot commented on Dec 9, 2020

    @css-meeting-bot
    Member

    The CSS Working Group just discussed [css-variables?] Higher level custom properties that control multiple declarations.

    The full IRC log of that discussion <dael> Topic: [css-variables?] Higher level custom properties that control multiple declarations
    <dael> github: https://github.com//issues/5624
    <dael> leaverou: There is a very reasonable tag guideline that custom elements shoudl use properties for presentational elements. With current state of custom properties this is impossible for non-trivial
    <dael> leaverou: Current custom prop can only be literal fragments and you need to transform
    <dael> leaverou: There are problems where we need to add inline conditionals.
    <dael> leaverou: However, when you have lots of these properties intersecting then it can get really messy if only 2 you have is inline funcitons that need both condisions.
    <dael> leaverou: Ideal is something to cascade but not sure feasible. Wanted impl feedback and then I can draft a more detailed proposal
    <dael> leaverou: Examples I've looks at from component liberties are in the issue
    <dael> leaverou: Some impl have weighed in in the issue [missed]
    <dael> leaverou: Wondering if set of constraints could be introduced to make it more feasable. Wanted to bring to attention of group for more ideas or thoughts
    <dael> astearns: Feedback on the shape of the feature?
    <dael> fremy: I think it's a pretty good idea.
    <dael> fremy: Really something that's a limitation of custom properties. Quite true when you use attributes you do more than reuse variable.
    <dael> fremy: Pseudo class you can't use in theory but it would be really nice to have syntactic sugar. I know you can do it meta languages. Good to auto-prefix with an if condition. That would give us most of advenatages. Extend the css selector syntax to have an id for all properties
    <TabAtkins> Assuming we're fine with simple conditionals in an if() function (which we've discussed before and this should be okay), doing an at-rule inside holding a block of props could have a reasonable desugaring to that.
    <dael> leaverou: One thing to keep in mind is these often need to control multiple elements in the component. Alignment might need to control margins and padding. Ideally should work
    <dael> leaverou: [missed]
    <TabAtkins> It would have some side-effects - any properties in the block are effectively using a variable, so it would kick in IACVT behavior, etc.
    <dael> leaverou: Often they need to control properties in mutli elements. Example alignment controls spaces, padding, etc in multi child elements. Good to keep in mind that it plays nicely with nesting module
    <dael> TabAtkins: invalid at computed value time = iacvt
    <fremy> @tabatkins: I would think it solves many issues
    <dael> leaverou: Some reasonable syntax to combine and falling back to invalid at computed value time would prob be acceptable
    <leaverou> As long as we can combine conditions and nest them, having IACVT as the ultimate fallback is acceptable
    <TabAtkins> so like `.foo { color: blue; @if (var(--state) = one) { color: red; } }`, it'd desugar to `.foo { color: cond(var(--state) = one, red; blue); }`
    <dael> astearns: I think this is a really interesting proposal and I'd like to see further discussion on what we can do here. Any major concerns about spending time on this?
    <dael> astearns: I think we should take this back to the issue and/or come up with a proposal which we can file issues on. IT's a really good idea. Anything else from group?
    <dael> leaverou: I primarily wanted to draw impl attention. I can't design impl needs. Continue on issue is fine
  11. FremyCompany commented on Dec 9, 2020

    @FremyCompany
    Contributor

    As mentioned above, I would like this to be pursued further. That sounds very useful (but even having if would be nice, I think).

    Random thought: another possible syntax for the syntactic sugar:

    selector {
        property-one: value;
        @transform-values if(--condition: true, $);
        property-two: value-x, value-y;
        property-three: value-u, value-v;
    }
    

    In the CSSOM, the @transform-values wouldn't be reflected, it would be a transform applied while parsing declarations.

    selector {
        property-one: value;
        property-two: if(--condition: true, value-x, value-y);
        property-three: if(--condition: true, value-u, value-v);
    }
    
  12. tabatkins commented on Dec 9, 2020

    @tabatkins
    Member

    So we'd previously discussed the cond() function as one of the "switch" variants, which would have effectively these exact semantics but grouped differently. That is, given Anders' example (lightly edited):

    my-input {
        border-radius: 0px;
    	@if (var(--pill) = on) {
    		border-radius: 999px;
    	}
    }
    

    it would be equivalent to the following using cond():

    my-input {
        border-radius: cond((var(--pill) = on) 999px; 0px);
    }
    

    (I wrote cond() as being essentially a math function, but simple equivalence for keywords seems reasonable to mix into here. These might want to use additional non-math comparators, like "is the value in this set", so we'd have to give it some thought and care.)

    The benefit of the at-rule syntax is that it inverts the grouping - when you have a bunch of variants of several properties, the at-rule groups them by variant, while cond() groups them by property. Which is more readable varies case-by-case, but when it matters it can have a large effect on the readability, particularly when the variants don't all affect the exact same set of properties. Noticing that sort of variation can be very hard when looking across several cond() functions.

    If we treat the two as exactly equivalent, just sugar variations of each other, then this does end up implying some slightly non-obvious behavior in some cases. For example, in:

    my-input {
    	@if (var(--pill) = on) {
    		color: green;
    	}
    }
    

    (Note the lack of "default" color in the block.) Then if --pill is off or whatever, color wouldn't just be not set, it would be IACVT and end up setting itself to inherit, which has some minor cascading implications. (This is presumably the behavior we'd define for cond() if you don't provide a default clause.)

    I don't think this is a big deal, it's just worth understanding the implications. I think this is much better than defining this as an almost identical feature that actually works completely differently under the covers.

  13. FremyCompany commented on Dec 9, 2020

    @FremyCompany
    Contributor

    Regarding Tab's proposal, we can do slightly better, and copy the value preceding the @if as a fallback:

    my-input {
            color: blue;
    	@if (var(--pill) = on) {
    		color: green;
    	}
    }
    

    would be either blue or green, by filling the fallback part of the cond with the already-existing value in the declaration (and only in the declaration, not across another selector, so that would still be a limitation, just a more convenient one because it allows to specify a default.

  14. 59 remaining items

  15. LeaVerou commented on May 27, 2021

    @LeaVerou
    MemberAuthor

    It's not ideal, but combined with an inline if() (that triggers IACVT) it could work.
    Shadow DOM elements would be able to style themselves based on properties on :host, right?

  16. andruud commented on May 27, 2021

    @andruud
    Member

    I don't think container-queries+ShadowDOM have been thought about thoroughly yet, but yes that sounds like what we'd want.

  17. LeaVerou commented on May 27, 2021

    @LeaVerou
    MemberAuthor

    That's the major use case, so whatever solution we pick needs to be able to work with that.

  18. LeaVerou commented on May 27, 2021

    @LeaVerou
    MemberAuthor

    Is the @container solution able to do other kinds of conditionals too? E.g. 1vw > 1em? Or only one custom property compared with one value? It would be nice if people can compare values of entire expressions instead of having to basically solve for x to find what the bounds are for the custom property, but that's a nice-to-have, not a dealbreaker. That would also allow them to have conditionals that depend on multiple custom properties.

  19. andruud commented on May 27, 2021

    @andruud
    Member

    That should be possible, provided that we can define what the operators mean and how things should evaluate. For example, in 1vw > 1em both sides might resolve to pixels, but for --x > 1em the left hand side resolves to a token sequence, the right hand side to pixels, so we'd need rules for how all of that should work. (In this case maybe @property is needed to make --x > 1em allowed)?

    It would be nice if people can compare values of entire expressions

    Mostly a matter of specifying the grammar + rules I think. Totally possible.

  20. LeaVerou commented on May 27, 2021

    @LeaVerou
    MemberAuthor

    Sure, but a lot of these rules are needed for if() anyway. The extra complexity of the @-rule is that they need to resolve in a way that is property-independent.

  21. muratcorlu commented on May 13, 2022

    @muratcorlu

    I just noticed this discussion after @johannesodland mentioned here in my proposal (#7273) for addressing the same issues in a different way. I completely agree about the needs we have here as @LeaVerou explained.

    Do you find useful, a solution like the below by having map-get function (as in older versions of SASS) to address the issues mentioned here?

    <my-button>Save</my-button>
    my-button {
       --size: small;
    }
    
    @media screen and (max-width: 900px) {
      my-button {
        --size: large;
      }
    }
    /* inside my-button component style */
    :host {
       padding: map-get((small: 4px  8px, regular: 8px 16px, large: 12px 24px), var(--size, regular));
    }

    More details are in #7273.

  22. Crissov commented on Feb 13, 2023

    @Crissov
    Contributor

    With the proposal in #3714 slightly extended for conditionals, a solution could look something like this:

    $pill {
      border-radius: 999px;
    }
    
    my-input {
      @include pill if (var(--pill) = "on");
    }
  23. trusktr commented on Jul 14, 2024

    @trusktr
    Member

    This can be implemented in CSS today using cyclic space toggles (I like to think of them like enums and switch cases).

    .foo {
      --size: var(--small);
      --theme: var(--dark);
      --placement: var(--top);
      --orientation: var(--vertical);
      --significance: var(--warning);
    }

    Although it isn't the most convenient, here's how something like --size can be implemented as a library author:

    /**
     * ## CSS library author code: ################################
     */
    button {
    	/* define the configurable option for the end user, with its default value */
    	--size: var(--size-medium);
    
    	/* define all the possible enum values for the option (commas are required, they enable the magic) */
    	--size-small: var(--size,);
    	--size-medium: var(--size,);
    	--size-large: var(--size,);
    	
    	/* finally apply output values using a switch case inside of each output property */
    
    	border:
    		solid deeppink
    		var(--size-small, 1px)
    		var(--size-medium, 2px)
    		var(--size-large, 3px);
    
    	border-radius:
    		var(--size-small, 2px)
    		var(--size-medium, 4px)
    		var(--size-large, 6px);
    
    	padding:
    		var(--size-small, 2px)
    		var(--size-medium, 4px)
    		var(--size-large, 6px);
    }

    Here's how an end user would use it:

    <button id="one">button</button>
    <button id="two">button</button>
    <button id="three">button</button>
    /**
     * ## End user code: ##########################################
     */
    #one {
    	/* end user picks the enum value they want */
    	--size: var(--size-small);
    }
    
    #two {
    	--size: var(--size-medium);
    }
    
    #three {
    	--size: var(--size-large);
    }

    where, depending on the picked --size, the component library will set a bunch of properties such as border-width, padding, margin, height, to various different values depending on the single value of --size, where --size is not just a length value.

    codepen example: CSS enums and switch-case logic

    Roman Komarov has some nice articles on it here: https://kizu.dev/layered-toggles/

    TLDR: yeah, maybe not entirely intuitive. But! Once the pattern is learned, it is easy to implement in libraries, and most importantly super easy for the end user to use.


    Using one of the syntax ideas above, here's the same thing in would-be new format:

    button {
    	--size: medium; /* possible values: small, medium, large */
    	
    	border:
    		solid deeppink
    		if(var(--size) = small, 1px)
    		if(var(--size) = medium, 2px)
    		if(var(--size) = large, 3px);
    
    	border-radius:
    		if(var(--size) = small, 2px)
    		if(var(--size) = medium, 4px)
    		if(var(--size) = large, 6px);
    
    	padding:
    		if(var(--size) = small, 2px)
    		if(var(--size) = medium, 4px)
    		if(var(--size) = large, 6px);
    }
    
    #one {
    	--size: small;
    }

    It is not a ton more terse, but the main advantage is that there is no cognitive overhead needed as with the space toggles. Someone who sees this code will know how it works without having to learn how space toggles and property cycles work.

    Paired with @property, IDEs could support type checking:

    @property --size {
        syntax: "small | medium | large";
        inherits: true;
        initial-value: medium;
    }

    (namespaced property names highly recommended)

  24. LeaVerou commented on Jul 14, 2024

    @LeaVerou
    MemberAuthor

    I’m well aware of cyclic toggles, but they are a hack/workaround, not something we can be content about as a solution and have quite a lot of limitations, not to mention the awkwardness of actual values having to be hidden behind variables.
    @kizu who came up with them is actually an Invited Expert in the group and has exactly the same opinion — in fact we used the ugliness of this and other hacks as an argument to convince the WG to resolve for if() in #10064

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

Metadata

Metadata

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions