Search code examples
csssasscss-variables

Is there a way to type check CSS custom properties (aka CSS variables)?


I'm considering replacing SCSS variables (i.e. $someValue) with CSS custom properties (e.g. var(--someValue)) in an attempt to both allow for a little more flexibility in the form of theming and context-specific overrides, and to make the devtools in browsers a little more usable. Eventually, I'd potentially like to dump SCSS variables entirely just to simplify the development stack.

However, I've noticed that unlike SCSS variables, CSS custom properties are entirely un-checked, and typos are a thing. I've had code break in confusing ways because a typo was made either setting a CSS custom property, or using it in an expression - after all, CSS is very lenient using un-set or invalidly set CSS properties.

Since CSS custom properties aren't exactly new at this point, I thought I'd be able to find some webpack plugin or other solution to add basic typechecking to CSS properties, but I can't seem to find any. Ideally, I'd like to require all CSS custom properties to be declared in some fashion, including something like a type for its contents (to ensure that e.g. variables are consistently used as a dimensionless vs. dimension-full value vs. color, etc), but even just a tool or technique to detect typos would catch real errors. However, I've been unable to find anything like this, either as a build tool, or SASS plugin.

How can I protect myself from simple oversights when using CSS custom properties, e.g. detect that a property set as --someValue: 13px is never used or conversely that a reference var(--someValue) appears to have no matching assignments?


Solution

  • Using the new @property rule you can almost have what you want since it will allow to define the type for your variables.

    Example:

    @property --primary-color {
      syntax: '<color>';
      inherits: false;
      initial-value: blue;
    }
    
    .box {
      --primary-color: red; /* this one is valid */
      background:var(--primary-color);
      height:100px;
    }
    
    .box-alt {
      --primary-color:10px; /* this one is invalid and will fall to the intial-value */
      background:var(--primary-color);
      border:var(--primary-color) solid green; /* it won't be used here even if contain pixel */
      height:100px;
    }
    <div class="box"></div>
    
    <div class="box-alt"></div>

    You need to run the above on Chrome or Edge (Firefox still doesn't support this). As you can see, using pixel value is not allowed here since we specified the type to be <color>.

    Actually the dev tool will show you nothing but this will probably change in the future to get some warning. In the meantime, you can rely on the initial value that will get used when the custom property is either not defined or defined with an invalid value.