How to view variable values in Sass


Sass logo

This week’s post is pretty technical—it’s only for users of Syntactically Awesome Stylesheets (Sass).

I’m leaving. Before I go, what is Sass?

Sass is a CSS preprocessor—a way to write your CSS stylesheets as if you were programming them, with variables, reusable mixins, and a lot else.

I can’t recommend Sass highly enough—it literally made possible my work on a recent client project. Of course, I had David to fool around with Ruby and the command line to get it installed in the first place. So if you’re pretty technically skilled and you’ve never used a preprocessor before, please give it a try.

I’m still here, to your surprise

That’s great news! Here we’re discussing a quick hack to output Sass variables directly to your browser, like this:
Sass variable values output in browser

Why this is useful?

In my recent experience with Sass, I’d sometimes hit a styling bug, and not know whether the problem was caused by:

  1. A variable being improperly set (perhaps somewhere I hadn’t expected)
  2. Proper variable values but incorrect styling rules

As far as I know, Sass has no at-a-glance way to view variable values as compiled into the site’s stylesheet. So today’s hack lets you view any Sass variable value you want in your browser, allowing for easier debugging.

How to do it

It’s simple, and uses the :before pseudo-selector applied to your body element:

  1. Find the Sass partial that has the styles for your body element
  2. Give the body element a :before pseudo-selector, as follows:
    How to output Sass variable values in browser
    Build the string after "content: " with as many previously declared variables as you want. (They don’t have to apply to your body element; they can apply to any part of your site.)

    Note that in Sass syntax, “&” means “the element we’re already working on”—body in this case, so &:before will compile to body:before in your stylesheet.

  3. Recompile your stylesheet, and check your browser. It should have text giving your variable values in the top left corner.

That’s it!

Voilà‎: easy tracking of Sass variable values through your browser.

Was this helpful? Have a better way to do it? We’d love to hear from you in the comments below!

3 thoughts on “How to view variable values in Sass

  1. Pingback: rUp: A Sass Function That Offers a Powerful Alternative to Ems | Press Up

  2. Pingback: ensureTextContrast(): A Sass function to preserve readability with variable fonts and colors | Press Up

  3. Pingback: Why I Wish I'd First Learned Programming in Sass | Press Up

Leave a Reply

Your email address will not be published. Required fields are marked *