12

I'm trying to optimise CSS-related calculations using two custom utility functions in Scss.

One for EMs:

@function _em($wanted, $inherited) {
  @return ($wanted / $inherited) + 'em';
}

...and another for percentages:

@function _pc($wanted, $parent) {
  @return (($wanted / $parent) * 100) + '%';
}

...then calling them inline:

body {
  margin: _pc(40,1024);
  font-size: _em(20,16);
  line-height: _em(26,20);
}

Neither of these are returning the expected Nem or N% string, however. (I think it's my string concatenation - i.e. gluing the unit declarative on the end of the calculation - but I'm not sure.)

Can anyone shed any light on what I'm doing wrong?

2 Answers 2

18

Actually, your problem is the name of the mixin. I just discovered this myself, but apparently you can't start a mixin with an underscore.

This works: http://jsfiddle.net/B94p3/

@function -em($wanted, $inherited) {
  @return ($wanted / $inherited) + 'em';
}

@function -pc($wanted, $parent) {
  @return (($wanted / $parent) * 100) + '%';
}

p {
    font-size: -em(40,16);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Ayman, though that's somewhat annoying. Think I'll just go with pc(x,y) and em(x,y) as prefixing function names with a minus could be misleading for other devs.
For reference for anyone who wants these, but without string output, just wrap the returns in SASS interpolation syntax, e.g.: @function -px-to-pc($wanted, $parent) { @return #{(( $wanted / $parent ) * 100 ) + '%'}; }
Thanks, Jasmine, this is the best solution—otherwise Sass seems to dump out the calculation+concatenation as a literal quoted string as the CSS rule value!
0

Similarly, I wrote this function for converting unit from px to rem.

You can modify accordingly.

$is-pixel: true;
$base-pixel: 16;

@function unit($value) {
  @if $is-pixel == true {
    $value: #{$value}px;
  } @else {
    $value: #{$value/$base-pixel}rem;
  }
  @return $value;
}

Now, one can use as following

.my-class {
  width: unit(60);
  height: unit(50);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.