Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lunelson
Last active October 18, 2015 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lunelson/5896b79bc2ce6f10df47 to your computer and use it in GitHub Desktop.
Save lunelson/5896b79bc2ce6f10df47 to your computer and use it in GitHub Desktop.
workup for "sass-calc" library
// ----
// Sass (v3.4.14)
// Compass (v1.0.3)
// ----
// str-lastindex -- get last index of substr in string
@function str-last-index($str, $substr) {
$length: str-length($str);
@for $n from $length - str-length($substr) through 1 {
$index: str-index(str-slice($str, $n, $length), $substr);
@if $index { @return $index + $n - 1; }
}
@return null;
}
// calc-pre -- prepare value for calc
@function calc-pre($value){
@if type-of($value) == 'string' {
$is-calc: str-index($value, 'calc') == 1;
$start: str-index($value, '(');
$end: str-last-index($value, ')');
@if $is-calc and $start and $end {
@return unquote(str-slice($value, $start, $end));
} @else {
@return unquote('(#{$value})');
}
} @else {
@return unquote('#{$value}');
}
}
// re-calc... ?
@function re-calc($calc1, $calc2, $op: '+'){
@return unquote('calc(#{calc-pre($calc1)} #{$op} #{calc-pre($calc2)})');
}
// add/sub -- both args can be calc()
@function calc-add($calc1, $calc2){ @return unquote('calc(#{calc-pre($calc1)} + #{calc-pre($calc2)})'); }
@function calc-sub($calc1, $calc2){ @return unquote('calc(#{calc-pre($calc1)} - #{calc-pre($calc2)})'); }
// mul/div -- second arg must be number
@function calc-mul($calc, $n){ @return unquote('calc(#{calc-pre($calc)} * #{$n})'); }
@function calc-div($calc, $n){ @return unquote('calc(#{calc-pre($calc)} / #{$n})'); }
$t: calc((5 - 2) * 3);
$start: str-index($t, 'calc');
$start2: str-index($t, '(');
$end: str-index($t, ')');
.test {
test: calc-pre($t);
test: calc-pre(calc((5 + 7) / 100));
test: calc-pre(calc(5));
test: calc-pre('3rem - 5em');
test: calc-pre(calc(3rem - 5em));
test: calc-pre(2);
test: calc-add(calc(3rem / 4), calc(10em - 2px));
test: calc-add(2rem, calc(10em - 2px));
test: calc-div(calc(3rem / 4), 4%);
test: re-calc(calc(3rem / 4), 4%, '-');
$width: calc(100vw - 100%);
margin-right: calc-add($width, 2rem);
margin-right: calc-sub($width, 2rem);
margin-right: calc-div($width, 2 - 4);
margin-right: calc-add(calc-mul($width, 2), 10em);
}
.test {
test: ((5 - 2) * 3);
test: ((5 + 7) / 100);
test: (5);
test: (3rem - 5em);
test: (3rem - 5em);
test: 2;
test: calc((3rem / 4) + (10em - 2px));
test: calc(2rem + (10em - 2px));
test: calc((3rem / 4) / 4%);
test: calc((3rem / 4) - 4%);
margin-right: calc((100vw - 100%) + 2rem);
margin-right: calc((100vw - 100%) - 2rem);
margin-right: calc((100vw - 100%) / -2);
margin-right: calc(((100vw - 100%) * 2) + 10em);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment