Search code examples
csspercentageadditionstylus

Stylus – Adding Percentages


I'm having trouble with Stylus. I'm simply trying to create a function which returns the width of a column given a span n. Here is my code:

column-gap = 1%
column-width = 15%

column-span(n)
(column-width * n) + (column-gap * (n - 1))

The problem is when n = 2 I'm expecting column-span to return 31%, but it instead returns 30.3%.

After some trial and error, I noticed that even this code complied to 30.3%:

30% + 1%

I'm not sure what's going on here.


Solution

  • Yeah, it's a bug in Stylus — it treats such input as if you're adding a percentage of the left part, so it adds the 1% of 30% to 30%.

    You can use a workaround here like this:

    column-span(n)
      (column-width * n) + unit(column-gap * (n - 1),"")
    

    the thing you're doing here is removing the unit from the second part of the expression, so it would treat it as 30% + 1, and in such cases Stylus would give you proper 31%.