Skip to content

Instantly share code, notes, and snippets.

@satya164
Last active September 7, 2023 20:06
Show Gist options
  • Save satya164/43950a19b23b6e2d7484 to your computer and use it in GitHub Desktop.
Save satya164/43950a19b23b6e2d7484 to your computer and use it in GitHub Desktop.
Quantity Queries in Sass
@mixin quantity-query($selector, $type, $amount, $max: null) {
@if $type == at-least {
#{$selector}:nth-last-child(n+#{$amount}),
#{$selector}:nth-last-child(n+#{$amount}) ~ #{$selector} { @content; }
} @else if $type == at-most {
#{$selector}:nth-last-child(-n+#{$amount}):first-child,
#{$selector}:nth-last-child(-n+#{$amount}):first-child ~ #{$selector} { @content; }
} @else if $type == between {
@if type-of($max) != "number" {
@error "Max value must be a number for quantity-query.";
}
#{$selector}:nth-last-child(n+#{$amount}):nth-last-child(-n+#{$max}):first-child,
#{$selector}:nth-last-child(-n+#{$amount}):nth-last-child(-n+#{$max}):first-child ~ #{$selector} { @content; }
} @else {
@error "Invalid type `#{$type}` for quantity-query. Allowed types - at-least, at-most, between.";
}
}
@satya164
Copy link
Author

Usage:

@include quantity-query("ul > li", at-least, 5) { color: blue; };

@include quantity-query(div, at-most, 3) { color: green; };

@include quantity-query(section p, between, 3, 5) { color: red; };

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