Home > Enterprise >  For loop is adding a space on generated CSS vars
For loop is adding a space on generated CSS vars

Time:03-30

This Less;

@sizes: xsmall, small, medium, medium-large, large, xlarge, xxlarge;

.init-spacing(@i) when (@i > 0) {
  
  @size: extract(@sizes, @i);
  
  // MARGINS --------------------------------------------
  .margin-@{size} { margin: var(--spacing-@size); }
  
  // PADDING --------------------------------------------
  .padding-@{size} { padding: var(--spacing-@size); }
  
  .init-spacing(@i - 1);
}

.init-spacing(length(@sizes));

Produces this output;

.margin-xxlarge {
  margin: var(--spacing- xxlarge); <-- Notice the added space.
}
.padding-xxlarge {
  padding: var(--spacing- xxlarge); <-- Notice the added space.
}
....

I'm curious why the css class names don't have an added space but their usage in the css vars being generated DOES have an added space. Most importantly, how do I get rid of that added space so the css vars are generated correctly valid?

Here's a Codepen to tinker with displaying the issue on the compiled css.

CodePudding user response:

The space is added by the concatenation of @size to --spacing-@size as less always adds a single space between the variables, eg the result of @size@size is xsmall xsmall.

To remove the unwanted space, use ~"--spacing-@{size}":

// MARGINS --------------------------------------------
.margin-@{size} { margin: var(~"--spacing-@{size}"); }
  
// PADDING --------------------------------------------
.padding-@{size} { padding: var(~"--spacing-@{size}"); }

Related Issue: https://github.com/less/less.js/issues/1375

  • Related