Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2018 by Frank Perez.

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

$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

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

$primaryHeaderFontSize = 4em
$contentFontSize = 1em

body
  font-size: 14px

h1
  font-size: $primaryHeaderFontSize

p
  font-size: $contentFontSize

Stylus Output

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

.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?

Stylus Output

.box {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  margin-left: -50px;
  margin-top: -50px;
  background-color: #00f;
}