You can also use interpolation to improve your functions for reuse, as well as your other code within your stylesheet. The way it works is that you can wrap your expression within {}, which will then be outputted as the identifier.
For instance, looking back at our border-radius function, we can take it another step forward. Instead of calling border-radius directly, we can make a helper method that works for other styles as well.
Stylus Code
vendor(prop, args)
-webkit-{ prop }: args
-moz-{ prop }: args
{ prop }: args
.box
width: 100px
height: 100px
background-color: blue
vendor(border-radius, 10px)
Notice that now we can simply call our vendor function along with the style, followed by the arguments for any style.
I personally prefer creating functions for specific styles. So let’s look at another possibility.
Stylus Code
vendor(prop, args)
-webkit-{ prop }: args
-moz-{ prop }: args
{ prop }: args
border-radius()
vendor(border-radius, arguments)
.box
width: 100px
height: 100px
background-color: blue
border-radius: 15px
Combining both options we’re able to come up with a far more readable approach, while keeping the repetitive code maintainable from a single location.
Selector Interpolation You can also use interpolation within your selectors. Let’s take an example where we loop through 10 div’s and changing the background-color of each alternating row.
Stylus Code
for row in 1..10
.product-row:nth-child({row})
background-color: (row % 2 == 0) ? green : blue
width: 100%
height: 20px
display: block
The above example loops through the number 1-10, while checking if each number is divisible by 2. When it is divisible by 2, then the background color is green, when it’s not the background color is blue.
There is a much better way to handle alternating colors, the above is just a simple example of showing you how you can easily use interpolation within your selectors.
Here’s the better example of accomplishing the above for you to reference.
Stylus Code
.product-row
width: 100%
height: 20px
display: block
.product-row:nth-child(even)
background-color: green
.product-row:nth-child(odd)
background-color: blue
You can also assign a list of selectors to a variable if needed.
Stylus Code
$item = '.product, .item'
{$item}
background-color: green
Stylus Output
.product,
.item {
background-color: #008000;
}