Setting Variables in Stylus

Unlike CSS, in Stylus you can assign expressions to variables that can be reusable throughout your stylesheets.

Let’s assume we had a set of colors that we’re going to be using throughout our document for headers, and text.

Stylus Code

1

2

3

4

5

6

7

8

9

$primaryFontColor=#262626

$headerColor=darkblue

body

color:$primaryFontColor

h1,h2,h3,h4,h5,h6

color:$headerColor

When creating variables, you do not need to include the $ dollar symbol. I use it here, as it stands out more to me letting me know that it is in fact a variable based on how variables are defined in the programming language I use from day to day.

Stylus Output

1

2

3

4

5

6

7

8

9

10

11

12

body{

color:#262626;

}

h1,

h2,

h3,

h4,

h5,

h6{

color:#00008b;

}

This is awesome. Now we can set base colors, or anything really to manage from 1 area. This will also help us keep on track to make sure we’re sticking to our brand colors and styles.

We may also want to set sizes for our primary headers and paragraphs.

Stylus Code

1

2

3

4

5

6

7

8

9

10

11

12

$primaryHeaderFontSize=4em

$contentFontSize=1em

body

font-size:14px

h1

font-size:$primaryHeaderFontSize

p

font-size:$contentFontSize

Stylus Output

1

2

3

4

5

6

7

8

9

10

body{

font-size:14px;

}

h1{

font-size:4em;

}

p{

font-size:1em;

}

Property Lookup/Reference

Another amazing feature of Stylus is the ability of looking up a properties value without having to assign it to a variable. For instance, let’s assume we want to create a box and center it to the page.

Stylus Code

1

2

3

4

5

6

7

8

9

10

.box

position:absolute

top:50%

left:50%

width:100px

height:100px

margin-left:-(@width/2)

margin-top:-(@height/2)

background-color:blue

You’ll see above that I was able to reference the width and height by simply typing @width or @height. How cool is that?

Tags

About This Blog

I'm writing this blog in order to share what I'm learning with the world. Since you learn best by teaching others and writing things down, I figured this would be the best way to really tackle any new technologies I plan on learning. I hope this blog will help you as much as it will benefit me.