Skip to content

Instantly share code, notes, and snippets.

@symmetriq
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save symmetriq/d87ae49232d4104c7f2e to your computer and use it in GitHub Desktop.
Save symmetriq/d87ae49232d4104c7f2e to your computer and use it in GitHub Desktop.
Add gaps between pairs of adjacent blocks or inline elements. Supports nesting.
// Generated by SassMeister.com
// ----
// Sass (v3.4.14)
// Compass (v1.0.3)
// ----
// Add a prefix to each item in a list
@function prependEach($items, $prefix) {
$output: ();
@each $item in $items {
$output: append($output, "#{$prefix}#{$item}", 'comma');
}
@return $output;
}
// Return only the last component of a selector chain.
// Supports comma-separated lists of chains.
@function selectorLeaves($selectors) {
$output: ();
@each $selector in $selectors {
$output: append($output, nth($selector, length($selector)), 'comma');
}
@return $output;
}
// Target adjacent elements with the same selector(s)
// Supports nesting (the entire selector is not repeated on both sides of '+')
@mixin adjacentSame {
$targets: prependEach(selectorLeaves(&), '+');
#{$targets} { @content }
}
// ----- Adjacent Gap -----
// use with multiple selectors to add spacing between any adjacent pair
// e.g.:
// a, .btn { @include adjacentGapInline(3px) }
// will add a 3px margin between: a + a, a + .btn, .btn + a, .btn + .btn
// gap between block elements uses margin-top
// (in the future this should use margin-block-start)
@mixin adjacentBlockGap ($gap) {
@include adjacentSame { margin-top: $gap }
}
// gap between inline elements uses margin-left
// (in the future this should use margin-inline-start)
@mixin adjacentInlineGap ($gap) {
@include adjacentSame { margin-left: $gap }
}
.this .works {
a, .btn { @include adjacentInlineGap(3px)}
}
// here's what would happen without the functions/mixin
.this .doesnt .work {
a, .btn {
& + & { margin-left: 3px }
}
}
.this .works a + a, .this .works a + .btn, .this .works .btn + a, .this .works .btn + .btn {
margin-left: 3px;
}
.this .doesnt .work a + .this .doesnt .work a, .this .doesnt .work .btn + .this .doesnt .work a, .this .doesnt .work a + .this .doesnt .work .btn, .this .doesnt .work .btn + .this .doesnt .work .btn {
margin-left: 3px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment