Skip to content

Instantly share code, notes, and snippets.

@zakirt
Last active July 25, 2017 09:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zakirt/db38c4b3a033a82bba2b to your computer and use it in GitHub Desktop.
Save zakirt/db38c4b3a033a82bba2b to your computer and use it in GitHub Desktop.
Sass mixin for styling elements based on sibling count.
// -----------------------------------------------------------------------------
// @author Zakir Tariverdiev
// @created August 2, 2014
// @desc Sass mixin that provides convenient way to style element's siblings.
// Based on the example from Lea Verou's blog:
// http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/
// @param (string) $sibling-count - number of expected siblings. You can also use
// use such forms as "n + 3" and "3n" for "at least 3 siblings" and
// "siblings divisible by 3," for example. These forms must be enclosed in
// quotes for proer parsing though.
// @param (string) $sibling - sibling element you wish to target. In most cases
// this parameter will need to be enclosed inside quotes for proper parsing.
// @param (string/optional) $every-nth - With this parameter, you can specify
// that only a specific sibling will have the specified styles applied to it.
// Ex. "3n + 1" will have the 1st and every 3rd sibling use the styles.
// Checkout example of this mixin in action here: http://codepen.io/zakirt/pen/wClId
// -----------------------------------------------------------------------------
@mixin sibglings-by-count($sibling-count, $sibling, $every-nth: null) {
$colon: ":"; // Can't use literal : in expressions, so we'll use this
@if ($every-nth) {
$sibling: #{$sibling}#{$colon}nth-child(#{$every-nth});
}
&:first-child:nth-last-child(#{$sibling-count}),
&:first-child:nth-last-child(#{$sibling-count}) ~ #{$sibling} {
@content;
}
}
@dbox
Copy link

dbox commented Apr 26, 2015

Been looking for this for a while! Have you ever written stylus? Any chance you could convert for it?

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