Skip to content

Instantly share code, notes, and snippets.

@balbuf
Last active February 6, 2019 19:22
Show Gist options
  • Save balbuf/fedd777bbd1dfd4c4a6665920dfe6987 to your computer and use it in GitHub Desktop.
Save balbuf/fedd777bbd1dfd4c4a6665920dfe6987 to your computer and use it in GitHub Desktop.
SASS function to generate nth formulas based on repeating patterns
// example output CSS
.container :nth-of-type(5n + 1), .container :nth-of-type(5n + 2), .container :nth-of-type(5n + 3) {
background: orange;
}
.container :nth-of-type(5n + 4), .container :nth-of-type(5n + 5) {
background: blue;
}
// example SASS
// first three elements are orange, next 2 elements are blue, next 3 elements are orange, etc. repeating in perpetuity
.container {
// 3 rows on, 2 rows off
#{nth-pattern(':nth-of-type()', 3 2)} {
background: orange;
}
// 2 rows on, 3 rows off, with a starting offset of 3 rows
#{nth-pattern(':nth-of-type()', 2 3, 3)} {
background: blue;
}
}
@function nth-pattern($selector, $pattern, $offset: 0) {
// add up the pattern values to get the total period length
$period: 0;
@each $value in $pattern {
$period: $period + $value;
}
// determine where we will stick the parenthetical formula
$insert-at: str-index($selector, "()");
@if $insert-at == null {
// default to tacking it on the end
$insert-at: str-length($selector) + 1;
} @else {
// strip out the placeholder
$selector: #{str-slice($selector, 0, $insert-at - 1) str-slice($selector, $insert-at + 2)};
}
// selector collector
$selectors: ();
// go through the pattern list
@for $i from 1 through length($pattern) {
// odd index is "on"
@if $i % 2 == 1 {
// add as many selectors as the value of this pattern item
@for $count from 1 through nth($pattern, $i) {
$selectors: append(
$selectors,
str-insert($selector, "(#{$period}n + #{$offset + $count})", $insert-at),
comma
);
}
}
// advance the offset
$offset: $offset + nth($pattern, $i);
}
@return $selectors;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment