Using CSS Stylus In Your Projects
Published: 2024-04-16 08:23:17

by [Christiana Uloma](https://blog.openreplay.com/authors/christiana-uloma) 

<blockquote><em>
In web design, efficiency and flexibility are key. [CSS Stylus](https://stylus-lang.com/) is a preprocessor that offers both by extending CSS's capabilities with powerful features like variables, mixins, functions, etc. This article will walk you through the process of integrating it into your project, providing step-by-step instructions and clear explanations for each code snippet while avoiding technical jargon.
</em></blockquote>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>



To begin, your system will need [Node.js](https://nodejs.org/en) installed. Once you have Node.js, you can install Stylus using [npm](https://www.npmjs.com/) (Node Package Manager) with the following command:
```bash
npm install -g stylus
```
This command installs Stylus globally on your system, allowing you to use it in any project.

After installing Node.js, you will create a new directory for your project and navigate into it:
```bash
mkdir my-stylus-project
cd my-stylus-project
```
The first command, `mkdir my-stylus-project`, creates a new directory named `my-stylus-project`. The second command, `cd my-stylus-project`, navigates into the newly created directory, allowing you to work within it.

Alternatively, you can follow these steps:

- Create a new folder.
- Open the folder in your text editor, preferably [VS Code](https://code.visualstudio.com/download).
- Open the integrated terminal in VS Code, and you're ready.

Next, you will initialize a new [npm](https://www.npmjs.com/) project:
```bash
npm init -y
```
This creates a `package.json` file, which will track your project’s dependencies.

You can manually compile Stylus files to CSS or use a task runner like [Gulp](https://gulpjs.com/). We will use a `script` in our `package.json` for simplicity.

Add the following line to the scripts section of your `package.json`:
```json
"compile-stylus": "stylus -w style.styl -o style.css"
```
After adding the `scripts`, you can run `npm run` `compile-stylus` to watch your Stylus file and compile it to CSS whenever changes are detected.

## Basic usage and syntax

Now that we have Stylus set up and running, let's dive into the basics of using it and explore its syntax. 

Stylus supports two syntax options: indented and bracketed. The indented syntax resembles a more streamlined and readable format, while the bracketed syntax aligns with traditional CSS syntax.

Here’s an example of Stylus code using indented syntax:
```css
body
  font 14px Helvetica, Arial, sans-serif
``` 
In Stylus, you can set multiple properties within a single line using the property value syntax. Therefore, in the above code, font is the property, and `14px` Helvetica, Arial, sans-serif is the value. The font size is set to `14px`, and the font family fallback list is specified as Helvetica, Arial, and sans-serif.

And the same code using bracketed syntax:
```css
body {
  font: 14px Helvetica, Arial, sans-serif;
}
```
Here, the font shorthand property sets the font size to `14px` and the font family to Helvetica, Arial, and sans-serif. The browser will attempt to use the first font in the list (Helvetica), and if it's unavailable, it will fall back to Arial. Similarly, if Arial is unavailable, it will fall back to a generic sans-serif font.

This is what the compiled CSS will look like:

![indented](https://blog.openreplay.com/images/using-css-stylus/images/image1.jpg)

Now that we know how Stylus works, let's move on to the use cases.👇

### Using variables and operators
 
In Stylus, [variables](https://stylus-lang.com/docs/variables.html) store and reuse values throughout your stylesheets. They allow you to assign a value to a variable name and use that name wherever the value is needed.

Here’s how to use them:
```css
font-stack = Helvetica, Arial, sans-serif
font-size = 14px

body
  font: font-size font-stack
```
In the above code, we define the `font-stack` variable to hold the value Helvetica, Arial, sans-serif and the `font-size` variable to hold the value `14px`. Then, within the body selector, we use the font property to apply the `font-size` variable followed by the `font-stack` variable, resulting in the desired font styling for the body element.

### Operators

[Operators](https://stylus-lang.com/docs/operators.html), on the other hand, are symbols or keywords used to perform various operations on values, such as arithmetic calculations, comparisons, logical operations, etc. 

Let's take this example:
```css
padding = 10px

body
  padding: padding * 2
```
This is a simple code that uses the operator keyword. In the code, we define the padding variable with a value of `10px`. Then, within the body selector, we use the padding property and apply the padding variable multiplied by `2`, resulting in the padding value of `20px` for the body element. 

Here's what the output for the variable and operator code will look like:

![variables](https://blog.openreplay.com/images/using-css-stylus/images/image2.jpg)


<CTA_Middle_Frameworks />



## Advanced features and functions

As you progress with Stylus, you can explore advanced features like mixins for reusable CSS declarations, functions and conditionals for adding logic and dynamic behavior to your styles, and utilize loops, lists, and hashes to write efficient and scalable code.

### Mixins 

[Mixins](https://stylus-lang.com/docs/mixins.html) are reusable blocks of code in Stylus that enable you to define a set of CSS declarations once and apply them to multiple selectors or elements. By encapsulating a group of styles into a mixin, you can conveniently reuse and share that code throughout your stylesheets, reducing code duplication and promoting a modular approach to styling.

Here’s a simple mixin for a border-radius:
```css
border-radius(radius)
  -webkit-border-radius: radius
  border-radius: radius

.box
  border-radius(5px)
```
In the code above, we define a mixin called `border-radius` that takes a parameter named radius. Within the mixin, we set the `-webkit-border-radius` property and the `border-radius` property to the radius value.

Then, we apply the `border-radius` mixin to the `.box` class with a parameter value of `5px`, which will set the border radius of the `.box` class to `5px`.

Here's what the compiled CSS will look like:

![mixin](https://blog.openreplay.com/images/using-css-stylus/images/image3.jpg)

### Functions

[Functions](https://stylus-lang.com/docs/functions.html), on the other hand, are similar to mixins in that they are reusable blocks of code, but with the added capability of returning a value. 

Here’s a function to convert pixels to rems:
```css
px-to-rem(px)
  return px / 16rem

body
  font-size: px-to-rem(14)
```
In the code above, we define a function called `px-to-rem` that takes a parameter named `px`. Within the function, we divide the given pixel value by `16rem` to convert it to `rem` units. The function then returns the calculated value.

Next, we apply the `px-to-rem` function to set the font size property of the body selector. We pass `14` as the parameter to `px-to-rem`, which converts `14px` to its equivalent value in `rem` units and sets it as the font size of the body element. 

The output will look like this: 

![function](https://blog.openreplay.com/images/using-css-stylus/images/image4.jpg)

### Loops 

[Loops](https://stylus-lang.com/docs/iteration.html) in Stylus provides a mechanism for repeating code blocks multiple times, allowing you to iterate over lists, perform operations on each element, and perform repetitive tasks efficiently. 

Here's an example of loops in Stylus:
```css
for num in (1..3)
  .padding-{num}
    padding: 10px * num
```
In the code above, we use a for loop to iterate over the range of numbers from `1` to `3`. Within each iteration, we generate a CSS class name using the format `.padding-{num}`, where `{num}` is the current number from the loop.

Inside the loop, we define the CSS rules for each generated class. In this case, we set the padding property to `10px` multiplied by the current number from the loop (`num`). This will result in three CSS classes: `.padding-1`, `.padding-2`, and `.padding-3`, each with a different padding value based on the loop iteration.

Here's what the compiled CSS will look like:

![loops](https://blog.openreplay.com/images/using-css-stylus/images/image5.jpg)

### Lists

[Lists](https://stylus.zcopy.site/docs/lists.html) refer to an ordered collection of values that can be accessed, iterated over, and manipulated, providing flexibility and convenience for handling groups of data.

Here's an example of lists in Stylus:
```css
colors = #ff0000 #00ff00 #0000ff

for color in colors
  .box-{color}
    background-color: color
```
Here, we define a list called `colors` that contains three color values in hexadecimal format. We then use a for loop to iterate over the colors list. We create a CSS class selector for each color in the list using the format `.box-{color}`. 

This will generate three CSS classes: `.box-#ff0000`, `.box-#00ff00`, and `.box-#0000ff`.

Here's what the compiled CSS will look like:

![list](https://blog.openreplay.com/images/using-css-stylus/images/image6.jpg)

As you can see, inside each generated CSS class, the `background-color` property is set to the corresponding color value using the colors variable.

### Hashes

[Hashes](https://stylus-lang.com/docs/hashes.html) refer to a data structure that stores key-value pairs, allowing you to associate values with specific keys for convenient and efficient data manipulation.

Let's take this example:
```css
fontSizes = {
  small: 12px,
  medium: 16px,
  large: 20px
}

for key, value in fontSizes
  .text-{key}
    font-size: value
```
In this code, we define a hash called `fontSizes` that associates different font sizes with corresponding keys (`small`, `medium`, and `large`). Next, we use a for loop to iterate over the `fontSizes` hash. We create a CSS class selector for each key-value pair in the hash using the format `.text-{key}`, which will generate three CSS classes: `.text-small`, `.text-medium`, and `.text-large`. 

Here's what the compiled CSS will look like:

![hash](https://blog.openreplay.com/images/using-css-stylus/images/image7.jpg)

Note: Inside each generated CSS class, the font-size property is set to the corresponding value using the value variable. 

Now, to use Stylus in your project, create an HTML file and link it to the compiled `style.css` file:

![stylusoutput](https://blog.openreplay.com/images/using-css-stylus/images/image8.jpg)

As you can see, the `style.css` is successfully linked to the HTML file.

After you have successfully linked your HTML file, you can start building your project. 

## Conclusion

Stylus is a robust CSS preprocessor that can significantly enhance your web development workflow. By understanding its syntax and features, you can write more maintainable and scalable CSS.

For further learning, check out:

- [Stylus official documentation](https://stylus-lang.com/)
- [Stylus GitHub repository](https://github.com/stylus/stylus)
 
These guides provide a foundational understanding of Stylus, aiming to be clear and free of technical jargon.