Jim R Web logo

Naming CSS Variables

This Isn’t the Fun Part

Naming things is hard. Maybe not so much for babies. But when it comes to code variables in absolutely every computer language invented, you will find strong opinions and totally different styles. I am no different, a naming nazi. So take it for what you paid here; disagreements and suggestions are more than welcome. Please let me know your perspective.

Casing Format and Size

camelCasing: I like to use camelCase for closely tied words in the description, “cobaltBlue,” “laughingBoyImage,” “imageShadowBlur,” and the like. The camelCasing style is an old C and Pascal naming holdover where the name can be a set of one or more descriptive words appended and every word except the first which is lowercase.  The name must be definitive. This part of the name is the identifier and distinguishes it from any other variables in a particular namespace. 

Namespaces: This gets my names into the more typical CSS kabob-casing; here each word is lowercase and separated by a hyphen or underscore. “system-control-breach-notification” would be a typical, but wordy, example.

My preferred style is to use kabob-casing to identify the namespace and class of a variable and then close with a camelCase identification. This restricts the number of hyphens and has a consistent labeling style. First, there is the namespace, then a hyphen and the class, and finally a hyphen and the identifier. Example: “system-color-elementorPrimary” also “padding-top-small.” But I will abbreviate the namespace and class to a two or three character mnemonic, so: “sys-clr-elePrimary” or “pad-tp-s” (I only have three sizes, small, medium, and large.)

Beyond that, if not in the :root{}, we should be in the namespace, so that lead-in would then be unnecessary.

What is the Name Describing?

Now we come to a real difference of opinion. Is the name part to be based on the value or the use? Most of the code I have seen is value-based: “sys-fnt-offBlack” or “btn-bkg-lgtTan.” I will do the same: “clr-fs-primary++” for a font color that is two shades darker than Primary
 

But I am always asking myself, “Was that ‘clr-fs-txt’, or was it ‘clr-fs-bdy?’ for a font color?” The value-based name makes for a very tight hierarchical structure. But sometimes it seems about as rememberable as just using HEX codes.