Stylus provides write a function with a group of CSS code. It is similar to mixins, However, Functions return data, and mixins do not return data. It also supports reusable code by supporting the DRY(Don’t Repeat Yourself) principle.

Stylus Functions

Like any programming language, Stylus contains function declaration and calling a function.

Function declaration contains the name of the function and body.

The function body contains arithmetic operators and returns values.

Syntax for Declare an function

functionname([arguments])
    body

functionname is the name of the function and valid identifier in Stylus. arguments are optional arguments the body is valid logic or arithmetic CSS code use the function below

element{
    functionname();
}

Here is an function example

widthCalculate(width1,padding1)
    width1+padding1

div{
width:widthCalculate(100px,10)
}

Output CSS:

div {
  width: 110px;
}

Stylus Default arguments in Functions

Sometimes, Arguments assign a default value.

In this example, the Second argument is assigned with the default value if the function is called with one argument.

widthCalculate(width1,padding1=20)
    width1+padding1

div{
width:widthCalculate(100px)
}

Output CSS:

div {
  width: 120px;
}

If function passes with second arguments, Default value is ignored

div{
width:widthCalculate(100px,50px)
}

Output:

div {
  width: 150px;
}

Function named parameters

As the arguments are passed based on the order of the parameters such as first and second.

We can also assign the names arguments and order is not required.

In this, names of arguments should match with passed arguments

widthCalculate(width1,padding1=20)
    width1+padding1

div{
width:widthCalculate(padding1:50px,width1:150px)
}

Compiled to

div {
  width: 200px;
}

Function return multiple values

Function not only returns a single value but returns multiple values.

It returns multiple values from an function

getWidthheight()
     100px 50px

first parameters can be get using functionname() with index=0, 1

div{
    width:getWidthheight()[0]
    height:getWidthheight()[1]
}

Compile to CSS

div {
  width: 100px;
  height: 50px;
}