70

In Stylus, how do I use a variable in a calc expression?

For example, the following doesn't work (arrow-size being a variable):

arrow-size = 5px
left calc(50% - arrow-size)
Kos
  • 4,890
  • 9
  • 38
  • 42
aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • 1
    Just in case you didn't know, Stylus lets you do the calculation directly: `left (50% - arrow-size)`. But I guess there might be times when you want the actual `calc` to show up – nachocab Nov 12 '17 at 11:54
  • 3
    `left (50% - arrow-size)` becomes `45%`, which isn't correct if you're mixing units like that. – Kael Watts-Deuchar Jan 28 '18 at 10:58

2 Answers2

115

In order to use a Stylus variable inside a calc expression, one must employ the string % operator:

arrow-size = 5px
left "calc(50% - %s)" % arrow-size
aknuds1
  • 65,625
  • 67
  • 195
  • 317
59

To use multiple variables (not just one) in calc (or with other functions), i use sprintf as you used, but with tuples:

arrow-size = 5px
measure = 50%
left "calc(%s - %s)" % (measure arrow-size)

Remember that interpolation in Stylus is supported through {} and it's used for other kind of interpolation. It's used to surround an expression, which then becomes part of a identifier, or a selector.

Thomas Urban
  • 4,649
  • 26
  • 32
Facundo Victor
  • 3,308
  • 1
  • 25
  • 20