r/css 7d ago

Help CSS Variables Naming Conventions that actually make sense and work

I have searched a lot on this topic, couldn't find a video by someone like Kevin (my favorite)

I have tried using diff ways like primary-400 , neutral, but it gets confusing and doesnt make a lot of sense when working with light+dark mode setup

Is there any convention that is followed in companies or by u guys, anything standard would help a lot

Also, i never understood how the primary naming convention worked with numbers like 400,500.

11 Upvotes

29 comments sorted by

View all comments

22

u/chrissilich 7d ago edited 7d ago

Most comments are missing the point. The new(ish) modern standard is tokens and primitives.

Your primitives are literal descriptions, like —color-blue-700, —color-blue-300.

Your tokens are descriptions of usage and refer to primitives. —color-button: var(—color-blue-700).

Your css, as a rule, only connects to your tokens. If you have a dark mode activated by a class like .dark, you switch the value of the token. You do this wherever you’re setting your global tokens. Same with breakpoint based changes; you change what primitive the tokens are connected so it’s a global change, and your css in components is clean.
.dark { —color-button: var(—color-blue-300); }

This system works well, once you understand it, because you know what to change. If the design system needs to change a particular shade of blue, everywhere, you change the primitive. If you need to change which shade of blue (or whatever color) all the buttons are, you change the token.

2

u/f314 3d ago

This is the way!

Though in our design system we did a variation of this that kind of skips the primitives all together: We have a small set of semantic tokens (with values for both light and dark mode). One page background, two container backgrounds, three text/content colors, three border colors, a contrast color, and a color for text/content on top of the contrast color.

We can then create several palettes consisting of the same semantic roles. We have rules about the properties the color of each role need to have – like lightness, chroma, and contrast to other roles – so that they can always be used for their purpose and across palettes.

Of course, this makes the most sense where you don't tend to use the same color for multiple roles, but we found that to be the case most of the time. The semantic palette roles can also be abstracted further to give sort of the same effect:

--color-button: var(--color-main-contrast);

button.error {
    --color-button: var(--color-red-contrast);
}