{"id":237831,"date":"2016-02-09T07:26:59","date_gmt":"2016-02-09T14:26:59","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=237831"},"modified":"2016-02-09T07:26:59","modified_gmt":"2016-02-09T14:26:59","slug":"power-function","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/snippets\/sass\/power-function\/","title":{"rendered":"Power Function"},"content":{"rendered":"
While very helpful with arithmetic, Sass falls a bit short with mathematical helper functions. There has been an open issue<\/a> on the official repository to ask for more math-related functions for almost 3 years. <\/p>\n Some third-party vendors like Compass<\/a> or SassyMath<\/a> provide advanced support for math features, but they are external dependencies which could (should?) be avoided.<\/p>\n One of the most popular request on this matter is a power function or even a exponent operator<\/a>. Unfortunately, there is still no support for this in Sass and while it is still under active discussion, it is unlikely to happen very soon.<\/p>\n Meanwhile, being able to raise a number to a certain power happens to be very useful in CSS. Here are a few examples where it would come in handy:<\/p>\n Fortunately for us, it is possible (and quite simple) to create a power function with nothing but Sass. All we need is a loop and some basic mathematical operators (such as Our function (named Here is an example:<\/p>\n However it only works with a positive `$power` argument. Allowing negative exponents wouldn\u2019t be so hard, we just need a small extra condition:<\/p>\n Here is an example:<\/p>\n Now, what if we want non-integer exponents? Such as \n
Sass implementation<\/h3>\n
*<\/code> and
\/<\/code>).<\/p>\n
Positive integer exponents<\/h4>\n
pow<\/code>) in its smallest form would look like this:<\/p>\n
@function pow($number, $exponent) {\r\n $value: 1;\r\n\r\n @if $exponent > 0 {\r\n @for $i from 1 through $exponent {\r\n $value: $value * $number;\r\n }\r\n }\r\n\r\n @return $value;\r\n}<\/code><\/pre>\n
.foo {\r\n width: pow(20, 2) * 1px; \/\/ 400px\r\n}<\/code><\/pre>\n
Positive or negative integer exponents<\/h4>\n
@function pow($number, $exponent) {\r\n $value: 1;\r\n\r\n @if $exponent > 0 {\r\n @for $i from 1 through $exponent {\r\n $value: $value * $number;\r\n }\r\n } @else if $exponent < 0 {\r\n @for $i from 1 through -$exponent {\r\n $value: $value \/ $number;\r\n }\r\n }\r\n\r\n @return $value;\r\n}<\/code><\/pre>\n
.foo {\r\n width: pow(10, -2) * 1px; \/\/ 0.0001px\r\n}<\/code><\/pre>\n
Positive or negative exponents<\/h4>\n
4.2<\/code> for instance? The truth is that it really is not easy. It still is doable, but it requires more than just a loop and a few operations.<\/p>\n