Skip to content

Instantly share code, notes, and snippets.

@adamgiese
Last active April 19, 2023 11:22
Show Gist options
  • Save adamgiese/717969cb38d4b30e1eff3d3abc6472f0 to your computer and use it in GitHub Desktop.
Save adamgiese/717969cb38d4b30e1eff3d3abc6472f0 to your computer and use it in GitHub Desktop.
Advanced nth-child mixins
@mixin valid-quantity($quantity) {
@if type-of($quantity) != 'number' {
@error 'The "quantity" parameter must be a number!';
}
@if not(unitless($quantity)) {
@error 'The "quantity" parameter must not have a unit!';
}
@if $quantity < 0 {
@error 'The "quantity" parameter must be at least 0!';
}
}
@mixin has-nth($expression, $element: '*') {
&:nth-last-child(#{$expression}):first-child,
&:nth-last-child(#{$expression}):first-child ~ #{$element} {
@content;
}
}
@mixin at-least($quantity, $element: '*') {
@include valid-quantity($quantity);
@include has-nth('n + #{$quantity}', $element) {
@content;
}
}
@mixin at-most($quantity, $element: '*') {
@include valid-quantity($quantity);
@include has-nth('-n + #{$quantity}', $element) {
@content;
}
}
@mixin divisible-by($quantity, $offset: 0, $element: '*') {
@include valid-quantity($quantity);
@include has-nth('#{$quantity}n + #{$offset}', $element) {
@content;
}
}
@mixin has-exactly($quantity, $element: '*') {
@include valid-quantity($quantity);
@include has-nth('#{$quantity}', $element) {
@content;
}
}
@mixin has-odd($element: '*') {
@include has-nth('odd', $element) {
@content;
}
}
@mixin has-even($element: '*') {
@include has-nth('even', $element) {
@content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment