Repository navigation
[css-color-4] Color modifications proposal: extending color functions #3187
Description
Edit: Most current proposal here, just go straight there unless you want to read the thread for historical reasons.
The lack of a color modification syntax is one of the few things that authors still use preprocessors for, and severely limits what CSS variables can do. I'm going to post this proposal I've been thinking about for a while. It's by no means perfect, but perhaps it can get the discussion going, so we end up with something decent eventually!
Goals of a color modification syntax
- Setting any color coordinates for all color functions, either to absolute values or to values relative to the modified color (e.g. set to 0.3 or increase by 50%)
- Avoiding accidental gamut clipping. If a syntax converts to sRGB, it should be syntactically obvious that this is happening.
- Easy lighter/darker variants (tint/shade)
- Blending of two or more colors
- Getting white or black depending on which one contrasts better with the base color
Proposal
This is loosely inspired from the current practice of defining major theme colors as color components in a variable (e.g. --color: 180, 60%) and then using them in color functions (e.g. hsl(var(--color), 90%)). However, this is simple textual substitution, which is insufficient, and imposes constraints on how the base color is defined.
I’m proposing to extend all color functions to allow for a <color> argument. If the color argument is present, it is converted to the target color space of the function, then the remaining arguments set or modify its coordinates in that color space. A _ or same keyword can be used to mean "no change". For example, if a function’s grammar is <number>{3}, it will become <color>? (<number> | _){3}.
For example, hsl(red _ _ 90%) would create an HSL color with a lightness of 90%, and the saturation and hue from the provided color.
Before any modification, the color would be converted to the target color space of the function used. This means that modifications using hsl() can be lossy (since the color would need to be converted to sRGB), but there is no such problem with lab() or lch(). However, any syntax that allows modifying HSL or RGB coordinates would have the same issue, at least this syntax makes the conversion more explicit.
Directly setting arguments is not sufficient for most modifications, since it cannot perform relative modifications (e.g. "increase L by 10%" instead of "set L to .3"), which are far more common use cases. Therefore, we need to introduce a syntax for relative modifications as well.
Ideas for that:
rel(<percentage>): Multiplies the color component by<percentage>. E.g.lab(red rel(60%) rel(100%) rel(100%))would convertredto Lab, and then multiply its L by 60%.up <percentage>/down <percentage>: Relative addition/subtraction. The previous example would belab(red down 40% up 0% up 0%). Given the lack of commas that we recently introduced, I'm finding this hard to read, since the keywords are not visually grouped with their percentages.- Defining keywords for each coordinate, then using
calc(). E.g. the previous example would belab(red calc(.4 * l) a b). Seems the most expressive and flexible, but probably too messy to define.
With the syntax for relative modifications, this addresses most desired adjustments, and expands naturally with every new color function. Tint and shade could be relative modifications on hwb(), though adjusting the L of Lab/LCH is better as it's lossless (and produces fantastic results).
Benefits of this syntax
- Extends on syntax that authors are already familiar with. No need to learn different ways to refer to the same color components.
- Can be understood by anyone who understands the existing color functions, even if they are unaware that a modification syntax exists.
- Makes the target color space very obvious, since it looks like creating a new color
- Every new color function comes with new color adjusters for free, no need to learn anything new besides using the color function.
Drawbacks
- Does not address contrasting colors
- Does not address blending of two or more colors. Perhaps these could be defined as separate functions, maybe
cross-fade(), since we need to address this for interpolation too? - It’s easy to clip the modified color to sRGB, since authors are very familiar with HSL and many would use that. However, any color adjustment syntax that supports adjusting hue, saturation, lightness would have the same issue. At least this syntax makes it obvious that you are creating an
hsl()color, with the gamut limitations that this comes with. - Stupid lossy transformations can be defined, like
color(hsl(color(mycmyk .1 .2 .3 .4) mycmyk 60%) .4). However, a) any sufficiently powerful syntax will allow for silly things, and b) see point above.
Activity
birtles commentedon Oct 1, 2018
Thank you for doing this. I'd love to see this happen.
I'm curious about how to make this apply to the underlying value so that you can, for example, have a generic
saturateclass, ordesaturateclass for that matter. We could define a syntax that applies to the cascaded value something likefont-size: largerdoes but that's a nightmare to implement (I suspect there are still plenty of animation edge cases here in particular) so I think we probably don't want to go that route. Perhaps we just need to define this in such a way that additive CSS will work, particularly now that we have definitions for how to add CSS values.For example, with the current addition facilities for animation one can already bump up the green channel by adding
rgb(0, 128, 0)to the underlying value but there's no facility for subtracting from a channel, nor operating on, say, the luminance channel.tabatkins commentedon Oct 2, 2018
I like the re-use of the existing color functions for modifying the channels in-place. I wouldn't make any of the arguments optional, tho; that seems both unnecessary and confusing - your
hsl(red 90%)example shows that off. It's not just a parsing problem, it's an understanding problem - to understand that, you need to recognize that90%can't be the first value, so it must be the second value.Instead, I think they should all be the same mandatory-ness as usual, and we use your
sameidea, or simplify it even more:hsl(red _ 90% _), with the_ident indicating that you take that value from the provided color. (And when values can be omitted, like alpha, they default to_, I guess?).LeaVerou commentedon Oct 3, 2018
Yeah, agreed. I guess then we need to find a syntax for same and relative values that is both sufficiently understandable and sufficiently terse. I’m a tiny bit worried that
_may be too terse, but mostly I think I like it.One benefit of the optional argument syntax that is now lost is that it's also a color space conversion syntax.
rgb(var(--mycolor))clips to sRGB,color(var(--mycolor) myCMYK)would convert to CMYK. Not sure how useful that was by itself and whether we want to preserve it. It can still be expressed viargb(var(--mycolor) _ _ _)andcolor(var(--mycolor) myCMYK _ _ _ _)respectively.birtles commentedon Oct 4, 2018
I was a bit concerned about how this overlaps with additive CSS―assuming that happens sometime in the near future.
On that one hand, additive CSS seems to provide something similar, i.e. presumably one could write
border-color: hsl(0deg 50% -50%) !addand we'd define it so it combines with the underlying value by converting as necessary to HSL first (and similarly for Lab etc. too).However, I think getting additive CSS to apply to a color in an arbitrary CSS variable is sufficiently awkward (you'd have to have a separate rule to make the underlying value use the CSS variable) that this proposal makes sense in its own right. This proposal is also a lot more elegant when altering the color component in a more complex value.
Crissov commentedon Oct 4, 2018
That is just like properties with optional values. We have all sorts of rules for which value is used to fill in missing ones. Iʼm not sure you are proposing the most intuitive one here.
hsl(red 90%)could expand to any of the following, all using the hue fromred:hsl(red 90% 90% 90%)– this and similar ones would make more sense ifhsl(0deg 90%)expanded tohsl(0deg 90% 90% 90%)hsl(red 90% 90% red)hsl(red 90% red 90%)hsl(red red 90% 90%)hsl(red 90% red red)– I believe this is the most systematic expansionhsl(red red 90% red)– assumed in the original proposal abovehsl(red red red 90%)With RGB, the single provided percentage value might even apply to the first, red channel.
LeaVerou commentedon Oct 4, 2018
Since Tab convinced me that optional arguments are a bad idea, I updated the original post so that it's not reflecting a proposal that even I don't support anymore, and so we can focus on the parts of the syntax that matter more.
Crissov commentedon Oct 4, 2018
🆗
With the keywords for coordinates idea, you would not need the underscore:
hsl(red h s 90%). Single letters may actually work better than words because ofrgb(red red green 90%).Martin-Pitt commentedon Oct 14, 2018
Had no idea that you can drop all the commas in those css functions. Wow, that feels weird and vague.
I like the idea of using single-letter keywords for placeholders as they match the functions' names. It creates a clear mapping. It only gets a bit weird when it comes to the alpha components on
lab/lchas we don't havelaba/lcha.What about keywords and +/-?
hsl(h s 50% from red), set lightness to 50% from the color redhsl(+20deg s l from green), rotate hue by +20deg from the color greenhsl(-15deg +10% -20% from lightblue), rotate hue by -15deg, add 10% saturation, subtract 20% lightness from the color lightblueOr:
hsl(red to h s 30%), set red to lightness of 30%hsl(darkblue to 0deg s +30%), set darkblue to hue of 0deg and add 30% lightnessI realise it might get confusing/conflict with absolute negative values. I think hsl can have negative hue values.
Perhaps there are ways to lean on
calcinstead as that is meant for number tweaking? Given the placeholders:hsl(calc(h + 5deg) calc(s + 10%) calc(l - 10%) from darkbrown)hsl(calc(h - 20deg) s l from blue)Testing longer keywords again:
hsl(calc(hue + 5deg) calc(saturation + 10%) calc(lightness - 10%) from darkbrown)I kind of like using
calcfor relative tweaking now that I think about it.hsl(h calc(s * 2 - var(--prop, 50%)) l from darkred)LeaVerou commentedon Oct 14, 2018
While keywords usually increase readability, in this case since there are no commas to group the different arguments. Therefore, keywords like
fromortoread like a separate argument, and don't look grouped with anything.Using
+and-to indicate relative modifications would indeed be the most readable, but unfortunately, it's not an option for disambiguation reasons. The parser sees+10%and10%as equivalent.I love the idea of using
calc()for tweaking! It would even work with the generic_we were discussing above. It would be the first case of using keywords incalc(), which may make it trickier to implement, but hopefully the flexibility is worth it? After all, we were always planning to use keywords incalc()eventually.AmeliaBR commentedon Oct 15, 2018
I like the idea of working with the syntax we've got, although complicating the arguments of the color functions is starting to make dropping the commas look like a bad idea.
There definitely needs to be some sort of grouping structure, even if it's just a mandatory wrapping
()without acalcprefix, so that you can distinguish addition /subtraction from simply setting the next number in the sequence. And distinguish division from the new syntax of using/to separate the alpha channel.I find the use of the component initials as the placeholder for the starting value more intuitive & easier to read than
_. But I recognize that there are long-term benefits to having a single token that works in any colour function, especially when you consider custom color systems. But maybe it could be both? The definitive syntax could use a generic placeholder, but allow the letters a synonyms in the common functions?I like the idea of using a
from <color>keyword approach, especially when you consider that the color would often be a variable, and some of the parameters may also be variables, so an extra keyword would help in readability.So, what I'm thinking of is something like this:
Re @birtles musing about an additive mode: we could define it so that the relative adjustments are valid without the
from <color>,bit. The color could default to transparent black, but in additive mode it could be whatever the base color in the adjustment stack is.tabatkins commentedon Oct 15, 2018
If one only needs the commas to put potentially-clashing complex grammars together, that suggests one should be using functions to contain the grammars instead; as an added bonus, you can then use commas in the function without clashing with the channel separator.
As an added bonus, functions give names to the functionality, which makes them easier to recognize and search for.
AmeliaBR commentedon Oct 15, 2018
Yeah, I kind of acknowledged that in my next sentence. It was just getting difficult to mentally parse some of the examples people were presenting earlier in the thread. I was sort of cheating by using brackets without a function name, but I agree with
That said, I'm concerned about reusing
calc()if we're also going to add a context-specific token. So my vote would be forrel()oradjust()or something like that. But I still like the idea of having a token for the current variable, to clearly distinguishrel(s + 20%)fromrel(s*20%).LeaVerou commentedon Oct 15, 2018
I agree that named components are far more intuitive, I'm just not sure what happens in the case of
color()and custom color profiles. I wonder if we can allow people to provide letters for the components in the@icc-profilerule (or whatever it's called) and default to a, b, c, d, ... otherwise?tabatkins commentedon Oct 15, 2018
Note an issue with single-letter names: lab() has both an "a" component and an alpha.
14 remaining items
svgeesus commentedon Jun 6, 2019
@AmeliaBR said
I like the generality of calc here. Although the examples so far have been restricted to simple arithmetic operators (+ - * /) on the current channel, it is an advantage to be able to compute from cusstom properties and to use the recently added calc trig functions, for example.
mirisuzanne commentedon Jun 6, 2019
I wonder if there is any useful overlap to be found between the
_proposal and other discussions about access to existing values?currentValue/cascadedValuein [css-cascade] Additive CSS #1594inherit()for vars in [css-values-5] inherit() function: like var() for parent value, for any property #2864calc(inherit)in [css-fonts] font-weight: bolder and lighter are counter-intuitive #2764They all deal with access to existing, previously-inaccessible values – often with a context-specific token in
calc(). Color-space metrics aren't the same as inherited values, but it seems useful to consider them in relation to each other.LeaVerou commentedon Jun 6, 2019
Btw as we discussed in the meeting, if the proposal is adopted, it won't be with
_but with keywords (not yet sure how that's gonna work withcolor()). I added a quick note to the post above to clarify this, and hopefully I can soon draft it up in Colors 5.svgeesus commentedon Feb 2, 2020
Lea has now added that proposal to the spec, see https://drafts.csswg.org/css-color-5/#relative-colors
Crissov commentedon Feb 3, 2020
This syntax with “local constants” allows to easily switch channels, e. g.
rgb(from currentcolor b g r), and it does allow inner colors defined in any valid syntax afterfrom, but authors are limited to the parameters of the outer functional notation they are using, i. e. they cannot access the ones of other notations. Iʼm not sure how useful this would actually be, but I assume authors would expect or even want to be able to do that nevertheless. Wouldnʼt it thus make sense to make them available as well?This would require unambiguous, multiple-letter monikers for some components of
hslandhwbvs.lch, andrgbvs.hwbvs.lab. The keyword for the opacity channel common to all notations is already speltalphainstead ofawhich would clash withlab.red[ness]is a<percentage>that corresponds to the origin color’s red channel after its conversion to sRGBgreen[ness]is a<percentage>that corresponds to the origin color’s green channel after its conversion to sRGBblue[ness]is a<percentage>that corresponds to the origin color’s blue channel after its conversion to sRGBhueis an<angle>that corresponds to the origin color’s HSL hue after its conversion to sRGB, normalized to a [0°, 360°) range.sat[uration]is a<percentage>that corresponds to the origin color’s HSL normalized chroma (i. e. saturation) after its conversion to sRGBlight[ness]is a<percentage>that corresponds to the origin color’s HSL lightness after its conversion to sRGBwhite[ness]is a<percentage>that corresponds to the origin color’s HWB whiteness after its conversion to sRGBblack[ness]is a<percentage>that corresponds to the origin color’s HWB blackness after its conversion to sRGBl-star/bright[ness]is a<percentage>that corresponds to the origin color’s CIE lightnessa-starorchroma[ticity]-ais a<number>that corresponds to the origin color’s CIELab greenish-reddish a axisb-starorchroma[ticity]-bis a<number>that corresponds to the origin color’s CIELab bluish-yellowish b axischromais a<number>that corresponds to the origin color’s LCH chromah-staris an<angle>that corresponds to the origin color’s LCH hue, normalized to a [0°, 360°) range.alphais a<percentage>that corresponds to the origin color’s alpha opacitytransparencyThis would also allow to make further values available in the future, which do not need to have dedicated notations, e. g. HSI
intensity(relative chroma), HSV relativevalue, HSB absolutebrightness;grayness; XYZtristimulus-x;luminosity(W, J/s), YUVluminance(lineary, nit, cd/m²), Y'UV / Y'CCluma(y-prime),chroma[ticity]-u,v-star,chroma-blue(Cb, Pb),red-cyan(Cr, Pr),chrominance,colorful[ness](saturation as relative colorfulness, chroma as comparative colorfulness;),blue-luminance(U),luma-v; YIQorangish-bluish(I),purple-green(Q), CMYKcyan[ness],magenta[ness],yellow[ness],key;tint,tone,shade;radiance…Btw., I believe it is counter-intuitive that angular hue would be converted to a
<number>, so I kept<angle>.svgeesus commentedon Feb 3, 2020
I can't imaging a use case for computing, say, 30% of the CIE L, 20% of the sRGB green channel, and 50% of the HSL hue.
Making the syntax more cumbersome to allow for a possibility with no use case does not seem like a win.
svgeesus commentedon Feb 3, 2020
@una wrote
@una has now added that proposal (as modified by CSS WG discussions in Toronto) to the spec too, and the co-editors have been working on illustrative examples.
color-mix()
color-contrast()
color-adjust()
Crissov commentedon Feb 4, 2020
Itʼs probably impossible to imagine realistic use cases for every color component combination, but finding a single one would already mean, that the identifiers needed to be unique across functional notations, in my humble opinion.
Would it be conceivable, for instance, that someone wanted to use CMYK
keyas HWBblackor itscyan,magentaandyellowcomponents as RGB channels?Would someone want to transplant an sRGB HSL hue or lightness into CIELab LCH?
You could effectively write custom conversion operations this way.
AmeliaBR commentedon Feb 4, 2020
When and if such use cases arise, the author could use nested functions. The result of one adjustment could be the "from" value for another adjustment.
Crissov commentedon Feb 20, 2020
@AmeliaBR I first thought this made absolute sense, but I cannot come up with some actual nested syntax that would result in
kfromdevice-cmyk()being used forbinhwb(), for instance.LeaVerou commentedon Dec 11, 2020
Btw, I posted some of the findings from HTTPArchive that relate to this in #5782.
svgeesus commentedon Jun 30, 2021
Closed by WG resolution to drop
color-adjust()and retain RCS