Understanding Sass Units

Originally published at: http://www.sitepoint.com/understanding-sass-units/

Understanding Sass Units

I have written about units in Sass in the past for my own blog, and not so long ago as a CSS-Tricks Sass snippet, but given how often I notice confusion and misconception about the way units work in our beloved preprocessor, I thought a full length article would not be such a bad idea after all.

After two years of writing and reading Sass code every day, I must say that snippets, articles and library code misusing Sass units are beyond counting. I have been guilty of this myself in the past, and I have witnessed Sass core designers trying to teach developers to properly use Sass units more than once.

This battle is obviously not over so let’s hope this article will be the coup de grace, in some way.

Units in real life

Before considering code, I think it is important to understand how numbers and units behave in real life. You may not have noticed this yet, but there are very few numbers we use in our daily life that do not have a unit. When we say “speed limit is 50″, we implicitly mean “50 kilometers per hour”; in this case the unit is km/h. When we say “look, eggs! I’ll have a dozen of those”, the unit is eggs: a dozen of eggs. There are exceptions of course but most usages of numbers in our daily routine usually involve a unit.

Along the same lines, running mathematical operations on numbers with units follow some rules. For instance, there are reasons why an area of 5 meters per 5 meters gives 25 square meters (). Same for a cube of 1 meter side: it has a volume of 1m3 because 1 meter per 1 meter per 1 meter doesn’t give 3 meters, but 1 cubic meter.

I like how Chris Eppstein puts it:

Continue reading this article on SitePoint
For instance, let’s say you want to convert seconds to milliseconds. I suppose you could divide the value by 1000 in order to have milliseconds

You write this, but it should be the other way around. If we have 42 seconds and want to convert it to milliseconds, we have to multiply with 1000.

In general, I totally agree with you and I hope that developers realize that this is the way to go.

2 Likes

Ouh, nice catch. We’ll fix it shortly. :slight_smile:

Done. Thank you @windmark

Though it’s a trivial task, it might be handy for some to also have a strip-units function example.

e.g.

@function strip-unit($num) {
  @return $num / ($num * 0 + 1);
}

When someone talks about feet i imagine this.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.