Search code examples
csscss-variables

Are periods allowed in CSS variable names?


For example could I have a css variable named like this: --Button.onHover?

Note that CSS variables are different from CSS selectors (I have to explain this because someone marked this as a duplicate). Here's an example from the module superfly-css-variables-colors:

      :root {
        --percentage-lightest:  91%;
        --percentage-lighter:   78%;
        --percentage-light:     65%;
        --percentage-median:    52%;
        --percentage-dark:      39%;
        --percentage-darker:    26%;
        --percentage-darkest:   13%;

        --percentage-low: 25%;
        --percentage-high:  50%;

        --percentage-link-hover: 25%;
      }

Solution

  • In CSS, property names are idents, and idents cannot contain a period. Per the CSS spec, they may only contain the characters [a-zA-Z0-9], hyphen -, underscore _, non-ASCII characters, as well as escaped versions of other characters. So it follows that property names cannot contain an unescaped period, and neither can custom property names.

    Therefore, --Button.onHover is not a valid custom property name (or "CSS variable" name, or whatever you want to call it).

    If you wanted to represent --Button.onHover as a valid CSS variable name, you'd have to escape the period, which can be done by prepending a backslash \ before it, or in the general case by running it through CSS.escape in JavaScript:

    console.log(CSS.escape('--Button.onHover')) // --Button\.onHover