Last active
February 6, 2019 19:22
-
-
Save balbuf/fedd777bbd1dfd4c4a6665920dfe6987 to your computer and use it in GitHub Desktop.
SASS function to generate nth formulas based on repeating patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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