Skip to content

Instantly share code, notes, and snippets.

@chrisross
Last active February 23, 2023 23:27
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisross/5935988 to your computer and use it in GitHub Desktop.
Save chrisross/5935988 to your computer and use it in GitHub Desktop.
This Sass (SCSS) function utilises the Greated Common Divisor (gcd) to reduce duplicate styles.
// Algorithm to calculate the Lowest Common Denominator
@function gcd($a, $b){
@if $b == 0 {
@return $a;
} @else {
@return gcd($b, $a%$b);
}
}
// Example Use-case:
//
// Mass generate classes for each percentage without duplicates
//
@for $i from 2 through 10 {
@for $ii from 1 to $i {
@if gcd($i,$ii) == 1 {
$percent: percentage(1/$i);
$fraction: #{$ii}-#{$i};
.col-#{$fraction} {
@extend %column;
width: get_width($amount);
}
}
}
}
//
// Outputs to css
//
// .col-1-2 { width: 50%; }
// .col-1-3 { width: 33.3333333%; }
// .col-2-3 { width: 66.6666666%; }
// .col-1-4 { width: 25%; }
// .col-2-4 { width: 50%; } <-- Doesn't get created
// .col-3-4 { width: 75%; }
// .col-1-5 { width: 20%; }
// .col-2-5 { width: 40%; }
// .col-3-5 { width: 60%; }
// .col-4-5 { width: 80%; }
// .col-1-6 { width: 16.6666666%; }
// .col-2-6 { width: 33.3333333%; } <-- Doesn't get created
// [etc...]
//
@billyhalim
Copy link

Why @if gcd($i,$ii) == 1 ? The value of returned by gcd($i, $ii) is different depend on the two values, not only 1. Explain please. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment